package com.yimi.yinhepda.views.unload_module;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.pda.uce.commom.util.LogUtil;
import com.pda.uce.commom.util.MyDialog;
import com.pda.uce.commom.util.Sp_net_Util;
import com.pda.uce.commom.util.ToastUtil;
import com.pda.ym.base.BaseActivity;
import com.pda.ym.callbacks.UICallBack;
import com.pda.ym.db.table.UnloadScanTable;
import com.pda.ym.entity.bean.CarPlanTaskEntity;
import com.pda.ym.entity.bean.LoadBillTaskEntity;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.ActivityStack;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.ym.utils.FastClick;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.pda.ym.utils.SysInfo;
import com.uce.pda.fragment.WarnFragment;
import com.uce.pda.module.WeightErrorPresenter;
import com.uce.pda.util.AlertDialogUtils;
import com.uce.pda.util.BlueToothUtil;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.UnLoadAdapter;
import com.yimi.yinhepda.db.dao.DepartmentTableDao;
import com.yimi.yinhepda.db.dao.JieLiuJianTableDao;
import com.yimi.yinhepda.db.dao.LoadUnloadGroupTableDao;
import com.yimi.yinhepda.db.dao.LoadUnloadTimeTableDao;
import com.yimi.yinhepda.db.dao.UCDeptTableDao;
import com.yimi.yinhepda.db.dao.UnloadScanTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.dao.UnloadUcTaskNoTableDao;
import com.yimi.yinhepda.db.helper.DbHelper;
import com.yimi.yinhepda.db.table.DepartmentTable;
import com.yimi.yinhepda.db.table.LoadUnLoadGroupTable;
import com.yimi.yinhepda.db.table.LoadUnloadTimeTable;
import com.yimi.yinhepda.db.table.UCDeptTable;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.db.table.UnloadUcTaskNoTable;
import com.yimi.yinhepda.entity.bean.UcTaskNoVo;
import com.yimi.yinhepda.entity.request.FinishTaskUploadRequest;
import com.yimi.yinhepda.entity.request.QueryCheckAdvancePayRequest;
import com.yimi.yinhepda.entity.request.QueryUnloadDetailRequest;
import com.yimi.yinhepda.entity.request.ScanLoadUploadRequest;
import com.yimi.yinhepda.entity.response.CheckAdvancePayResponse;
import com.yimi.yinhepda.entity.response.LoadInfo;
import com.yimi.yinhepda.entity.response.QueryLoadDetailBillcode;
import com.yimi.yinhepda.entity.response.QueryLoadDetailChildBillcode;
import com.yimi.yinhepda.entity.response.QueryStorageAreaResponse;
import com.yimi.yinhepda.entity.response.QueryUnLoadDetailBillcode;
import com.yimi.yinhepda.entity.response.QueryUnloadDetailResponse;
import com.yimi.yinhepda.entity.response.QueryWaybillByChildNoResponse;
import com.yimi.yinhepda.entity.response.WaybillInfo;
import com.yimi.yinhepda.event.CountEvent;
import com.yimi.yinhepda.event.CreateStowagesEvent;
import com.yimi.yinhepda.event.ScanResult;
import com.yimi.yinhepda.utils.BigDecimalUtils;
import com.yimi.yinhepda.utils.CheckNetTimeUtil;
import com.yimi.yinhepda.utils.Common;
import com.yimi.yinhepda.utils.HiddenAnimUtils;
import com.yimi.yinhepda.utils.ListUtils;
import com.yimi.yinhepda.utils.ThreadPoolUtils;
import com.yimi.yinhepda.utils.UcWaybillValidate;
import com.yimi.yinhepda.views.load_module.DetailsActivity;
import com.yimi.yinhepda.views.load_module.LoadUnloadGroupActivity;
import com.yimi.yinhepda.views.load_module.LoadUtil;
import com.yimi.yinhepda.views.unload_module.UnBlocking.BlockingUnloadTaskActivity;
import com.yimi.yinhepda.views.unload_module.palletbind.PalletBindActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.yimi.yinhepda.utils.Common.mQueryLoadDetailBillcode;

/**
 * 卸车扫描界面
 *
 * @author 000432
 */
public class UnloadScanActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener,
        RadioGroup.OnCheckedChangeListener, BlueToothUtil.BlueTooth {
    /**
     * 上个界面传过来的车牌号、主键、上一站名称
     */
    private String carNo, task, deptCode;
    private UnLoadAdapter adapter;
    private TextView num, nextStation, totlepiao, scanedpiao, totlejian, scanedjian;
    private UnloadScanTableDao mUnloadScanTableDao;
    private DepartmentTableDao mDepartDao;
    private ListView listView;
    private Button btnAdd;
    /**
     * 操作类型，操作码:1 -装车，2- 卸车
     */
    private int operTypeCode = 2;
    /**
     * 输入方式 1-PDA扫描输入,2-手动输入
     */
    private int inputType = 1;
    /**
     * 是否首次进入这个界面
     */
    private boolean isfirst = true;
    private boolean isFirstTime = true;
    /**
     * 是否退出上传线程
     */
    private boolean isExit = false;
    /**
     * 卸车数据
     */
    private List<QueryUnLoadDetailBillcode> unloadDataEntityList = new ArrayList<>();
    public static Map<String, List<QueryUnLoadDetailBillcode>> stowageNoMap;
    private List<String> stowageNos;
    public static final int UNLOADSCAN_RESULT = 102;
    public static final int UNLOADSCAN_RESULT_103 = 103;
    /**
     * 卸车当前站（下一站）
     */
    private List<String> mCurrentDeptCodes;
    /**
     * 串货提示对话框
     */
    private MyDialog chuanhuoDialog;
    private String mTempResult;
    /**
     * 装卸组参与的装卸人
     */
    private String joinWrokNum;
    private String joinUserName;
    /**
     * 月台号
     */
    private String platformNo;
    private int deptType;
    /**
     * 扫描描述
     */
    private TextView tvShowDesc;
    /**
     * 装卸组按钮
     */
    private Button btnLoadUnloadGroup;
    /**
     * 托盘绑定勾选框
     */
    private CheckBox cbPalletBind;
    /**
     * 超长件勾选框
     */
    private CheckBox cbChaoChangJian;
    /**
     * 超长件单选框组合
     */
    private RadioGroup rgChaoChangJian;
    /**
     * 超长件单选框
     */
    private RadioButton rbChaoChangJian1, rbChaoChangJian2, rbChaoChangJian3;
    /**
     * 超长件：1=1.8-2.5，2=2.51-2.8,3=2，8以上
     */
    public static Integer chaoChangJian;
    /**
     * 托盘绑定按钮
     */
    private Button btnPalletBind;
    /**
     * 托盘绑定数据
     */
    private List<QueryUnLoadDetailBillcode> mPalletBindList;
    /**
     * 托盘任务号
     */
    private String mPalletTaskNo;
    /**
     * 绑定绑定数量
     */
    private TextView tvPalletBindNo;
    private int mPalletBindNum = 0;
    /**
     * 绑定票数
     */
    private TextView tvBindPiaoNo;
    private int mBindPiaoNum = 0;
    /**
     * 列表头部
     */
    private LinearLayout listHead;
    /**
     * 显示绑定数量布局
     */
    private LinearLayout llPalletBindNum;
    /**
     * 向下箭头按钮
     */
    private ImageView ivDownLayout;
    /**
     * 要显示和隐藏的布局
     */
    private LinearLayout llFunctionBtn;
    /**
     * 卸车时间.
     */
    private TextView tvUnloadTime;
    /**
     * 快运、快递复选框、异形件
     */
    public static CheckBox cbKuaiYun, cbKuaiDi, yiXingJian;
    /**
     * 卸车倒计时(分钟) 总计费重量÷1分钟/100KG=卸车总时长
     */
    private int mUnloadTime;
    /**
     * 卸车秒数倒计时
     */
    private int mUnloadSeconds;
    /**
     * 卸车任务倒计时
     */
    private Timer mTimer;
    private long mMinute = 0;
    private int timeSS = 60;
    private boolean isScan = false;
    private LoadUnloadTimeTableDao loadUnloadTimeTableDao;
    private List<UcTaskNoVo> mUcTaskNoVoList;

    private boolean isUcOneTask;
    private boolean isYmOneTask;

    public static Handler mHandler;
    public static final int HANDLER_100 = 100;
    public static final int HANDLER_101 = 101;
    public static final int HANDLER_102 = 102;
    public static final int HANDLER_103 = 103;
    public static final int HANDLER_104 = 104;
    /**
     * 中心到件的卸车任务
     */
    public static List<UnloadTaskTable> zxdjTasks;
    /**
     * 配载单是否是第一次扫描标志
     */
    private boolean isFirstScan = true;
    private Handler checkTimeHandler = new Handler();
    /**
     * 融合：卸车任务集合
     */
    private List<CarPlanTaskEntity> mPlanTaskList;
    /**
     * 快递称重重量
     */
    public static BigDecimal mUcWeight;
    public static boolean isBlueConnected;
    private JieLiuJianTableDao mJieLiuJianTableDao;
    private UnloadTaskTableDao mUnloadTaskDao;
    private LoadUnloadGroupTableDao mLoadGroupDao;
    private boolean isClickSubmit;

    /**
     * 间隔300秒(五分钟)，自动校验时间
     */
    private long loadTime = 1000 * 300;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (!isDoing) {
                //网络时间校验
                String compCode = SharedPreferUtil.getInstance().getCompanyCode();
                String empCode = SharedPreferUtil.getInstance().getWorkNum();
                String pwd = SharedPreferUtil.getInstance().getPwd();
                CheckNetTimeUtil.checkNetworkTime(UnloadScanActivity.this, compCode, empCode, pwd, true, null);
            }
            // 间隔300秒(五分钟)
            checkTimeHandler.postDelayed(this, loadTime);
        }
    };

    @SuppressLint("HandlerLeak")
    private void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HANDLER_100:
                        //托盘绑定请求扫描
                        Bundle bundle = msg.getData();
                        String result = bundle.getString("result");
                        doScan(result);
                        break;
                    case HANDLER_101:
                        //绑定提交后，清空托盘，重置托盘任务号，重置卸车托盘绑定标志为未扫描
                        mPalletTaskNo = Constants.getPalletTaskNo();
                        mPalletBindList.clear();
                        break;
                    case HANDLER_102:
                        //托盘绑定删除数据后，重置托盘list
                        bundle = msg.getData();
                        mPalletBindList = (List<QueryUnLoadDetailBillcode>) bundle.getSerializable("palletBindList");
                        break;
                    case HANDLER_103:
                        bundle = msg.getData();
                        String mm = bundle.getString("mm");
                        String ss = bundle.getString("ss");
                        deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
                        if (deptType != 5 && deptType != 6) {
                            //网点
                            if ("29".equals(mm) && "59".equals(ss)) {
                                SoundVibratorManager.playVibrator(UnloadScanActivity.this, 3000);
                                showToastTime("离规定卸车时间还有30分钟！", 3000);
                            }
                        }
                        if (Integer.parseInt(mm) < 30) {
                            tvUnloadTime.setTextColor(getResources().getColor(R.color.red));
                        } else {
                            tvUnloadTime.setTextColor(getResources().getColor(R.color.black));
                        }
                        tvUnloadTime.setText(mm + ":" + ss);
                        break;
                    case HANDLER_104:
                        if (!isScan) {
                            //卸车开始倒计时
                            startCountDown(mUnloadTime, mUnloadSeconds);
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }

    /**
     * 卸车开始倒计时
     */
    private void startCountDown(long minutes, int remainSecond) {
        isScan = true;
        if (remainSecond == 0) {
            minutes--;
        }
        mMinute = minutes;
        if (remainSecond != 0) {
            timeSS = remainSecond;
        }
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (mMinute < 0 || mMinute <= 0 && timeSS <= 0) {
                    mTimer.cancel();
                    Bundle bundle = new Bundle();
                    bundle.putString("mm", "00");
                    bundle.putString("ss", "00");
                    Message msg = new Message();
                    msg.setData(bundle);
                    msg.what = HANDLER_103;
                    mHandler.sendMessage(msg);
                    return;
                }
                if (timeSS <= 0) {
                    mMinute--;
                    timeSS = 60;
                }
                timeSS--;
                long mm = mMinute;
                long ss = timeSS % 60;
                String mmStr = "";
                String ssStr = "";
                if (mm < 10 && mm >= 0) {
                    mmStr = "0" + mm;
                } else {
                    mmStr = mm + "";
                }
                if (ss < 10) {
                    ssStr = "0" + ss;
                } else {
                    ssStr = ss + "";
                }
                Bundle bundle = new Bundle();
                bundle.putString("mm", mmStr);
                bundle.putString("ss", ssStr);
                Message msg = new Message();
                msg.setData(bundle);
                msg.what = HANDLER_103;
                mHandler.sendMessage(msg);
            }
        }, 0, 1000);
    }

    @Override
    public void handleBarCode(final String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            Context context = ActivityStack.getInstance().currentActivity();
            if (context instanceof UnloadScanActivity) {
                handleScanResult(result);
            }
        }
    }

    /**
     * 处理扫描结果
     */
    private void handleScanResult(final String result) {
        long scanLastTime = sharedPreferUtil.getLongValue(Common.SCAN_LAST_TIME);
        long currentTime = System.currentTimeMillis();
        if (isFirstScan || currentTime - scanLastTime > 1000 * 300) {
            isFirstScan = false;
            //每次进入界面校验网络时间,或者扫描时间超过五分钟
            String compCode = SharedPreferUtil.getInstance().getCompanyCode();
            String empCode = SharedPreferUtil.getInstance().getWorkNum();
            String pwd = SharedPreferUtil.getInstance().getPwd();
            CheckNetTimeUtil.checkNetworkTime(this, compCode, empCode, pwd, false, new UICallBack() {
                @Override
                public void onError(String msg) {
                    if (msg.equals(Constants.PLEASE_CHECK_NET)) {
                        doScan(result);
                    }
                }

                @Override
                public void onSuccess(Object obj) {
                    doScan(result);
                }
            });
        } else {
            doScan(result);
        }
    }

    /**
     * 处理扫描
     */
    private synchronized void doScan(String result) {
        //本地记录扫描最后时间
        sharedPreferUtil.setLongValue(Common.SCAN_LAST_TIME, System.currentTimeMillis());

        if (!isScan) {
            //卸车开始倒计时
            startCountDown(mUnloadTime, mUnloadSeconds);
        }

        if (!StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result) && !UcWaybillValidate.validate(result)) {
            SoundVibratorManager.playSound(2);
            showToast("单号或包号不规范!(" + result + ")");
            return;
        }

        if (isUcOneTask && !UcWaybillValidate.validate(result)) {
            SoundVibratorManager.playSound(2);
            showToast("非快递运单号!(" + result + ")");
            return;
        }

        if (isYmOneTask && !StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("非快运单号!(" + result + ")");
            return;
        }

        //获取装卸组信息
        getGroupInfo();

        if (StringUtils.isWaybillNo(result) || StringUtils.isPackgeNo(result)) {
            //快运单号
            QueryLoadDetailChildBillcode detailChild = null;
            Iterator<QueryUnLoadDetailBillcode> it = unloadDataEntityList.iterator();
            while (it.hasNext()) {
                QueryUnLoadDetailBillcode unLoadDetailBillcode = it.next();
                if (!result.startsWith(unLoadDetailBillcode.getWaybillNo())) {
                    // 主单号是否存在其中，不存在下一个
                    continue;
                }
                // 如果是大票货，只能添加000尾号的子单
                if (unLoadDetailBillcode.isBigTicket() && !"000".equals(result.replace(unLoadDetailBillcode.getWaybillNo(), ""))) {
                    showToast("(" + result + ")单号不符合规范，大票货子单尾号为000");
                    return;
                } else if (!unLoadDetailBillcode.isBigTicket() && "000".equals(result.replace(unLoadDetailBillcode.getWaybillNo(), ""))) {
                    showToast("(" + result + ")单号不符合规范，非大票货子单尾号不能为000");
                    return;
                }

                if (unLoadDetailBillcode.getChildList() != null && !unLoadDetailBillcode.getChildList().isEmpty()) {
                    for (QueryLoadDetailChildBillcode detailChildBillcode : unLoadDetailBillcode.getChildList()) {
                        if (result.equals(detailChildBillcode.getChildWaybillNo())) {
                            if (detailChildBillcode.getFlag() == 1) {
                                if (PalletBindActivity.mHandler == null) {
                                    SoundVibratorManager.playSound(2);
                                    showToast("运单号已扫描！(" + result + ")");
                                }
                                /**添加托盘绑定数据*/
                                addPalletBindData(result, unLoadDetailBillcode, 2);
                                return;
                            }

                            /**判断该子单号是否已打印，未打印给出提示，并打断扫描*/
                            boolean isBePrint = isBePrintChileWayBill(unLoadDetailBillcode, detailChildBillcode);
                            if (!isBePrint) {
                                return;
                            }

                            //设置已扫描
                            detailChildBillcode.setFlag(1);
                            detailChild = detailChildBillcode;

                            //库存件数为0则为强扫
                            String remark = "";
                            if (unLoadDetailBillcode.getPiecesNum() == null || unLoadDetailBillcode.getPiecesNum() == 0) {
                                remark = "2";
                            }

                            int goodsPriority = 0;
                            if (unLoadDetailBillcode.getGoodsPriority() != null) {
                                goodsPriority = Integer.parseInt(unLoadDetailBillcode.getGoodsPriority());
                            }

                            //插入表
                            UnloadScanTable mUnloadScanTable =
                                    new UnloadScanTable(task, unLoadDetailBillcode.getWaybillNo(), result, unLoadDetailBillcode.getPackageNo(),
                                            //detailChild.getStowageNo() == null ? unLoadDetailBillcode.getStowageNo() : detailChild.getStowageNo(),
                                            unLoadDetailBillcode.getStowageNo(), operTypeCode, inputType, remark, unLoadDetailBillcode.getAreaCode(),
                                            SharedPreferUtil.getInstance().getValue(Common.USER_CODE), SharedPreferUtil.getInstance().getValue(Common.USER_NAME),
                                            Constants.GetSysTime(), Constants.GetScanTime(), SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE),
                                            SysInfo.getInstance().getImei(), unLoadDetailBillcode.getCarNo(), 0, goodsPriority, unLoadDetailBillcode.getProductType(), joinWrokNum, joinUserName, deptType,
                                            //waybillType：1-快运，2-快递
                                            mPalletTaskNo, platformNo, sharedPreferUtil.getValue(Common.MOVE_IN_PLACE_CODE),
                                            1, unLoadDetailBillcode.getTaskNo(), null, yiXingJian.isChecked() ? 1 : 0);
                            mUnloadScanTable.setRelationDeptCode(unLoadDetailBillcode.getRelationDeptCode());
                            mUnloadScanTable.setRelationDeptName(unLoadDetailBillcode.getRelationDeptName());
                            mUnloadScanTable.setRelationDeptType(unLoadDetailBillcode.getRelationDeptType());
                            mUnloadScanTable.setWeight(unLoadDetailBillcode.getWeight());
                            try {
                                if (mUnloadScanTableDao.insert(mUnloadScanTable) <= 0) {
                                    SoundVibratorManager.playSound(2);
                                    showToast("插入数据库失败！");
                                    return;
                                }
                            } catch (SQLException e) {
                                LogUtil.e(e.toString());
                                showToast("卸车插入数据异常：" + e.toString());
                                return;
                            }
                            //更新显示信息
                            scanedjian.setText((Integer.parseInt(scanedjian.getText().toString()) + 1) + "");
                            if (unLoadDetailBillcode.getScanCount() == 0) {
                                scanedpiao.setText((Integer.parseInt(scanedpiao.getText().toString()) + 1) + "");
                            }
                            //未扫描数+1
                            addUnloadCount();

                            it.remove();
                            /**添加托盘绑定数据*/
                            addPalletBindData(result, unLoadDetailBillcode, 1);
                            if ("1".equals(unLoadDetailBillcode.getGoodsPriority()) && !unLoadDetailBillcode.isBiRemind()) {
                                //扫描到必走货，黑框加震动替提示，按票提醒
                                unLoadDetailBillcode.setBiRemind(true);
                                showToast("此运单为必走货！");
                                SoundVibratorManager.playVibrator(UnloadScanActivity.this, 2000);
                            }
                            SoundVibratorManager.playSound(1);
                            unloadDataEntityList.add(0, unLoadDetailBillcode);
                            //根据复选框类型显示运单列表
                            showInfosByCheckBox();
                            return;
                        }
                    }
                }
            }
            if (detailChild == null) {
                Iterator<QueryUnLoadDetailBillcode> itDetail = unloadDataEntityList.iterator();
                while (itDetail.hasNext()) {
                    QueryUnLoadDetailBillcode unLoadDetailBillcode = itDetail.next();
                    // 主单号是否存在其中，不存在下一个
                    if (!result.startsWith(unLoadDetailBillcode.getWaybillNo())) {
                        continue;
                    }

                    unLoadDetailBillcode.setRemark("2");
                    detailChild = new QueryLoadDetailChildBillcode();
                    detailChild.setChildWaybillNo(result);
                    detailChild.setFlag(1);
                    detailChild.setStowageNo(unLoadDetailBillcode.getStowageNo());
                    if (unLoadDetailBillcode.getChildList() == null) {
                        unLoadDetailBillcode.setChildList(new ArrayList<QueryLoadDetailChildBillcode>());
                    }
                    unLoadDetailBillcode.getChildList().add(0, detailChild);

                    int goodsPriority = 0;
                    if (unLoadDetailBillcode.getGoodsPriority() != null) {
                        goodsPriority = Integer.parseInt(unLoadDetailBillcode.getGoodsPriority());
                    }
                    //插入表
                    UnloadScanTable mUnloadScanTable =
                            new UnloadScanTable(task, unLoadDetailBillcode.getWaybillNo(), result, unLoadDetailBillcode.getPackageNo(),
                                    //detailChild.getStowageNo() == null ? unLoadDetailBillcode.getStowageNo() : detailChild.getStowageNo(),
                                    unLoadDetailBillcode.getStowageNo(), operTypeCode, inputType, unLoadDetailBillcode.getRemark(), unLoadDetailBillcode.getAreaCode(),
                                    SharedPreferUtil.getInstance().getValue(Common.USER_CODE), SharedPreferUtil.getInstance().getValue(Common.USER_NAME),
                                    Constants.GetSysTime(), Constants.GetScanTime(), SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE),
                                    SysInfo.getInstance().getImei(), unLoadDetailBillcode.getCarNo(), 0, goodsPriority, unLoadDetailBillcode.getProductType(), joinWrokNum, joinUserName, deptType,
                                    //waybillType：1-快运，2-快递
                                    mPalletTaskNo, platformNo, sharedPreferUtil.getValue(Common.MOVE_IN_PLACE_CODE), 1,
                                    unLoadDetailBillcode.getTaskNo(), null, yiXingJian.isChecked() ? 1 : 0);
                    mUnloadScanTable.setRelationDeptCode(unLoadDetailBillcode.getRelationDeptCode());
                    mUnloadScanTable.setRelationDeptName(unLoadDetailBillcode.getRelationDeptName());
                    mUnloadScanTable.setRelationDeptType(unLoadDetailBillcode.getRelationDeptType());
                    mUnloadScanTable.setWeight(unLoadDetailBillcode.getWeight());
                    try {
                        if (mUnloadScanTableDao.insert(mUnloadScanTable) <= 0) {
                            SoundVibratorManager.playSound(2);
                            showToast("插入数据库失败！");
                            return;
                        }
                    } catch (SQLException e) {
                        LogUtil.e(e.toString());
                        showToast("卸车扫描保存数据异常：" + e.toString());
                        SoundVibratorManager.playSound(2);
                        return;
                    }
                    //更新显示信息
                    scanedjian.setText((Integer.parseInt(scanedjian.getText().toString()) + 1) + "");
                    if (unLoadDetailBillcode.getScanCount() == 0) {
                        scanedpiao.setText((Integer.parseInt(scanedpiao.getText().toString()) + 1) + "");
                    }
                    //未扫描数+1
                    addUnloadCount();

                    itDetail.remove();
                    /**添加托盘绑定数据*/
                    addPalletBindData(result, unLoadDetailBillcode, 1);
                    if ("1".equals(unLoadDetailBillcode.getGoodsPriority()) && !unLoadDetailBillcode.isBiRemind()) {
                        //扫描到必走货，黑框加震动替提示，按票提醒
                        unLoadDetailBillcode.setBiRemind(true);
                        showToast("此运单为必走货！");
                        SoundVibratorManager.playVibrator(UnloadScanActivity.this, 2000);
                    }
                    SoundVibratorManager.playSound(1);
                    unloadDataEntityList.add(0, unLoadDetailBillcode);
                    //根据复选框类型显示运单列表
                    showInfosByCheckBox();
                    break;
                }
            }
            if (detailChild == null) {
                //子单下载主单
                downloadWaybillNo(result);
            }
        } else if (UcWaybillValidate.validate(result)) {
            //快递单号

            //快递中心到件，预付款校验
            if (unloadDataEntityList != null) {
                for (QueryUnLoadDetailBillcode unLoadDetailBillcode : unloadDataEntityList) {
                    if (result.startsWith(unLoadDetailBillcode.getWaybillNo())) {
                        if (zxdjTasks != null) {
                            for (UnloadTaskTable taskTable : zxdjTasks) {
                                if (taskTable.getStowageNo().equals(unLoadDetailBillcode.getStowageNo())) {
                                    //扫描的运单的配载单属于中心到件,调用接口，查询预付款，入参：当前部门、运单号
                                    queryCheckAdvancePay(result);
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            if (isBlueConnected) {
                if (mUcWeight != null) {
                    int i = mUcWeight.compareTo(BigDecimal.ZERO);
                    if (i == -1 || i == 0) {
                        MyDialog.showAlertDialog(this, "蓝牙称重重量不能为0！");
                        return;
                    }
                }
            }

            //处理快递单号
            handleScanUCResult(result);

        } else {
            showToast("未知运单号！");
        }
    }

    /**
     * 查询预付款校验
     */
    private void queryCheckAdvancePay(final String waybillNo) {
        showPgDlg("运单校验中...");
        QueryCheckAdvancePayRequest request = new QueryCheckAdvancePayRequest();
        //当前登录部门
        request.setSrcDeptCode(sharedPreferUtil.getDeptCode());
        request.setChildWaybillNo(waybillNo);
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(CheckAdvancePayResponse.class)
                .setUrl(Constants.URL_CHECK_ADVANCE_PAY)
                .setRequestObject(request)
                .setConnTimeOut(15 * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        handleScanUCResult(waybillNo);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        CheckAdvancePayResponse response = (CheckAdvancePayResponse) obj;
                        if (response != null && response.getData() != null) {
                            if (response.getData().isSuccess()) {
                                MyDialog.showAlertDialog(UnloadScanActivity.this, "提示", response.getData().getMessage(), "确定");
                                SoundVibratorManager.playSound(2);
                                return;
                            }
                        }
                        handleScanUCResult(waybillNo);
                    }
                });
    }

    /**
     * 处理扫描快递运单
     */
    private void handleScanUCResult(String result) {
        //判断是否是截留件
        if (Common.isJieLiuJian(this, result, mJieLiuJianTableDao)) {
            return;
        }

        if (unloadDataEntityList != null) {
            final Iterator<QueryUnLoadDetailBillcode> it = unloadDataEntityList.iterator();
            while (it.hasNext()) {
                final QueryUnLoadDetailBillcode unLoadDetailBillcode = it.next();
                if (unLoadDetailBillcode.getWaybillNo().equals(result)) {
                    if (unLoadDetailBillcode.getChildList() != null) {
                        for (QueryLoadDetailChildBillcode childBillcode : unLoadDetailBillcode.getChildList()) {
                            if (childBillcode.getChildWaybillNo().equals(result)) {
                                if (childBillcode.getFlag() == 1) {
                                    if (!FastClick.isFastClickScanner()) {
                                        //重复扫描提示
                                        Context currentContext = ActivityStack.getInstance().currentActivity();
                                        if (!(currentContext instanceof PalletBindActivity)) {
                                            SoundVibratorManager.playSound(2);
                                            LoadUtil.showDeleteWaybillDialog(currentContext, result, null,
                                                    unLoadDetailBillcode, 22, mPlanTaskList, 2, new UICallBack() {
                                                        @Override
                                                        public void onError(String msg) {

                                                        }

                                                        @Override
                                                        public void onSuccess(Object obj) {

                                                            //强扫的快递运单，撤销后直接冲列表中删除
                                                            if ("2".equals(unLoadDetailBillcode.getRemark())) {
                                                                it.remove();
                                                            }

                                                            //根据复选框类型显示运单列表
                                                            showInfosByCheckBox();
                                                        }
                                                    });
                                        } else {
                                            /**添加托盘绑定数据*/
                                            addPalletBindData(result, unLoadDetailBillcode, 1);
                                        }
                                    }
                                    return;
                                }
                                //设置为扫描状态
                                childBillcode.setFlag(1);
                            }
                        }
                    }
                    unLoadDetailBillcode.setUcScan(true);

                    //插入表
                    UnloadScanTable mUnloadScanTable =
                            new UnloadScanTable(task, unLoadDetailBillcode.getWaybillNo(), result, unLoadDetailBillcode.getPackageNo(),
                                    unLoadDetailBillcode.getStowageNo(), operTypeCode, inputType, null, unLoadDetailBillcode.getAreaCode(),
                                    SharedPreferUtil.getInstance().getValue(Common.USER_CODE), SharedPreferUtil.getInstance().getValue(Common.USER_NAME),
                                    Constants.GetSysTime(), Constants.GetScanTime(), SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE),
                                    SysInfo.getInstance().getImei(), unLoadDetailBillcode.getCarNo(), 0, null, unLoadDetailBillcode.getProductType(), joinWrokNum, joinUserName, deptType,
                                    //waybillType：1-快运，2-快递
                                    mPalletTaskNo, platformNo, sharedPreferUtil.getValue(Common.MOVE_IN_PLACE_CODE), 2,
                                    unLoadDetailBillcode.getTaskNo(), chaoChangJian, yiXingJian.isChecked() ? 1 : 0);
                    mUnloadScanTable.setWeight(mUcWeight);
                    if (mUcWeight != null) {
                        mUnloadScanTable.setChargedWeight(mUcWeight.toString());
                    }
                    unLoadDetailBillcode.setWeight(mUcWeight);
                    unLoadDetailBillcode.setChargedWeight(mUcWeight);

                    try {
                        if (mUnloadScanTableDao.insert(mUnloadScanTable) <= 0) {
                            SoundVibratorManager.playSound(2);
                            showToast("插入数据库失败！");
                            return;
                        }
                    } catch (SQLException e) {
                        LogUtil.e(e.toString());
                        showToast("UC卸车插入数据异常：" + e.toString());
                        return;
                    }
                    scanedjian.setText(String.format("%s", Integer.parseInt(scanedjian.getText().toString()) + 1));
                    scanedpiao.setText(String.format("%s", Integer.parseInt(scanedpiao.getText().toString()) + 1));
                    //未扫描数+1
                    addUnloadCount();

                    it.remove();

                    unloadDataEntityList.add(0, unLoadDetailBillcode);
                    //根据复选框类型显示运单列表
                    showInfosByCheckBox();
                    //声音提示
                    soundRemind();

                    /**添加托盘绑定数据*/
                    addPalletBindData(result, unLoadDetailBillcode, 1);

                    //发送消息处理手动添加结果
                    ScanResult scanResult = new ScanResult(result, 8, 7);
                    scanResult.setWaybillNo(unLoadDetailBillcode.getWaybillNo());
                    EventBus.getDefault().post(scanResult);

                    //设置最近扫描时间
                    FastClick.setLastClickTimeScanner();
                    return;
                }
            }
        }

        /***不在配载列表内扫描，为强扫，查询库区信息***/
        queryUCStorageInfo(result);
    }

    /**
     * 声音提示
     */
    private void soundRemind() {
        Context currentContext = ActivityStack.getInstance().currentActivity();
        if (currentContext instanceof UnloadScanActivity) {
            if (chaoChangJian != null && yiXingJian.isChecked()) {
                SoundVibratorManager.playSound(7);
            } else if (chaoChangJian != null) {
                SoundVibratorManager.playSound(4);
            } else if (yiXingJian.isChecked()) {
                SoundVibratorManager.playSound(6);
            } else {
                SoundVibratorManager.playSound(1);
            }
        }
    }

    private void queryUCStorageInfo(final String result) {
        showPgDlg("查询库区中...");
        Map param = new HashMap<String, String>(1);
        param.put("waybillNo", result);
        new NetRequest().setUrl(Constants.URL_GET_UC_STORAGE_CODE)
                .setMethod(NetRequest.Method.GET)
                .setParams(param)
                .setResponsClazz(QueryStorageAreaResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        enableScan();
                        dismissPgDlg();
                        //合并数据到内存，并插入当前条码到数据库
                        handleUCForceScan(result, null);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        enableScan();
                        dismissPgDlg();
                        QueryStorageAreaResponse response = (QueryStorageAreaResponse) obj;
                        if (response != null) {
                            QueryStorageAreaResponse.Data data = response.getData();
                            if (data != null) {
                                //合并数据到内存，并插入当前条码到数据库
                                handleUCForceScan(result, data);
                            } else {
                                handleUCForceScan(result, null);
                            }
                        } else {
                            handleUCForceScan(result, null);
                        }
                    }
                });
    }

    /**
     * 处理快递强扫
     */
    private void handleUCForceScan(String result, QueryStorageAreaResponse.Data data) {
        LoadBillTaskEntity tempLoadTask = null;
        for (CarPlanTaskEntity planTask : mPlanTaskList) {
            if (planTask.getLoadTasks() != null) {
                for (LoadBillTaskEntity loadTask : planTask.getLoadTasks()) {
                    if (!loadTask.getStowageNo().startsWith("P")) {
                        if (tempLoadTask == null) {
                            loadTask.setTaskNo(planTask.getTaskNo());
                            tempLoadTask = loadTask;
                        }
                    }
                }
            }
        }

        QueryUnLoadDetailBillcode unLoadDetailBillcode = new QueryUnLoadDetailBillcode();
        unLoadDetailBillcode.setTaskNo(tempLoadTask.getTaskNo());
        unLoadDetailBillcode.setWaybillNo(result);
        unLoadDetailBillcode.setUcScan(true);
        if (tempLoadTask != null) {
            unLoadDetailBillcode.setStowageNo(tempLoadTask.getStowageNo());
            if (tempLoadTask.getCarNo() != null) {
                unLoadDetailBillcode.setCarNo(tempLoadTask.getCarNo());
            }
        } else {
            showToast("没有匹配到快递任务！");
            return;
        }
        unLoadDetailBillcode.setSrcPiecesNum(1);
        unLoadDetailBillcode.setPiecesNum(1);
        unLoadDetailBillcode.setRemark("2");
        //创建UC快递子单
        QueryLoadDetailChildBillcode childBillcode = new QueryLoadDetailChildBillcode();
        childBillcode.setChildWaybillNo(result);
        childBillcode.setStowageNo(unLoadDetailBillcode.getStowageNo());
        childBillcode.setFlag(1);
        List<QueryLoadDetailChildBillcode> childBillcodeList = new ArrayList<>();
        childBillcodeList.add(childBillcode);
        unLoadDetailBillcode.setChildList(childBillcodeList);

        if (data != null) {
            if (data.getStorageCode() == null) {
                unLoadDetailBillcode.setAreaCode("");
            } else {
                unLoadDetailBillcode.setAreaCode(data.getStorageCode());
            }
            if (data.getNextDeptCode() == null) {
                unLoadDetailBillcode.setNextDeptCode("");
            } else {
                unLoadDetailBillcode.setNextDeptCode(data.getNextDeptCode());
            }
            if (data.getNextDeptName() == null) {
                unLoadDetailBillcode.setNextDeptName("");
            } else {
                unLoadDetailBillcode.setNextDeptName(data.getNextDeptName());
            }
        }

        //插入表
        UnloadScanTable mUnloadScanTable =
                new UnloadScanTable(task, unLoadDetailBillcode.getWaybillNo(), result, unLoadDetailBillcode.getPackageNo(),
                        unLoadDetailBillcode.getStowageNo(), operTypeCode, inputType, unLoadDetailBillcode.getRemark(),
                        unLoadDetailBillcode.getAreaCode(), SharedPreferUtil.getInstance().getValue(Common.USER_CODE),
                        SharedPreferUtil.getInstance().getValue(Common.USER_NAME), Constants.GetSysTime(), Constants.GetScanTime(),
                        SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE), SysInfo.getInstance().getImei(),
                        unLoadDetailBillcode.getCarNo(), 0, null, unLoadDetailBillcode.getProductType(),
                        //waybillType：1-快运，2-快递
                        joinWrokNum, joinUserName, deptType, null, platformNo, sharedPreferUtil.getValue(Common.MOVE_IN_PLACE_CODE),
                        2, unLoadDetailBillcode.getTaskNo(), chaoChangJian, yiXingJian.isChecked() ? 1 : 0);
        mUnloadScanTable.setWeight(mUcWeight);
        if (mUcWeight != null) {
            mUnloadScanTable.setChargedWeight(mUcWeight.toString());
        }
        unLoadDetailBillcode.setWeight(mUcWeight);
        unLoadDetailBillcode.setChargedWeight(mUcWeight);
        try {
            if (mUnloadScanTableDao.insert(mUnloadScanTable) <= 0) {
                SoundVibratorManager.playSound(2);
                Toast.makeText(UnloadScanActivity.this, "插入数据库失败！", Toast.LENGTH_LONG).show();
                return;
            }
        } catch (SQLException e) {
            showToast("强扫卸车数据保存异常：" + e.toString());
            return;
        }
        scanedjian.setText(String.format("%s", Integer.parseInt(scanedjian.getText().toString()) + 1));
        scanedpiao.setText(String.format("%s", Integer.parseInt(scanedpiao.getText().toString()) + 1));

        //未扫描数+1
        addUnloadCount();
        unloadDataEntityList.add(0, unLoadDetailBillcode);
        //根据复选框类型显示运单列表
        showInfosByCheckBox();
        //声音提示
        soundRemind();

        /**添加托盘绑定数据*/
        addPalletBindData(result, unLoadDetailBillcode, 2);

        //发送消息处理手动添加结果
        ScanResult scanResult = new ScanResult(result, 8, 7);
        scanResult.setWaybillNo(unLoadDetailBillcode.getWaybillNo());
        EventBus.getDefault().post(scanResult);

        //设置最近扫描时间
        FastClick.setLastClickTimeScanner();
    }

    /**
     * 判断该子单号是否已打印，未打印给出提示
     *
     * @param unLoadDetailBillcode 主单实体
     * @param childBean            子单实体
     */
    private boolean isBePrintChileWayBill(QueryUnLoadDetailBillcode unLoadDetailBillcode, QueryLoadDetailChildBillcode childBean) {
        if (childBean.getBePrint() == null) {
            return true;
        }
        if (childBean.getBePrint() == 2) {
            //字段为2或者空-已打印
            return true;
        } else if (childBean.getBePrint() == 1) {
            //1-未打印，禁止扫描
//            MyDialog.setTag(1);
            MyDialog dialog = MyDialog.getInstance(this);
            dialog.setIcon(R.drawable.alert);
            dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
            dialog.setTitle("系统提示");
            dialog.setMessage("该票货发生目的站更改，请补打标签更换！");
            dialog.setPositiveClickListener("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    MyDialog.setNull();
                }
            });
            dialog.setCancelable(false);
            dialog.setCanceledOnTouchOutside(false);
            if (unLoadDetailBillcode.getScanCount() == 0) {
                //扫描第一件做打断提示
                //设置该标志，不返回扫描结果
//                MyDialog.setTag(1);
                try {
                    dialog.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        }
        return true;
    }

    private void downloadWaybillNo(final String result) {
        disableScan();
        showPgDlg("正在子单下载主单...");

        Map param = new HashMap();
        param.put("childWaybillNo", result);

        new NetRequest().setUrl(Constants.URL_FORCE_SCAN)
                .setMethod(NetRequest.Method.GET)
                .setParams(param)
                .setResponsClazz(QueryWaybillByChildNoResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        enableScan();
                        dismissPgDlg();
                        if (msg.equals(Constants.PLEASE_CHECK_NET)) {
                            queryStorageCode(null, result);
                        } else {
                            SoundVibratorManager.playSound(2);
                            //显示强扫错误中止扫描提示对话框
                            showForceScanErrorDialog(msg);
                        }
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        QueryWaybillByChildNoResponse response = (QueryWaybillByChildNoResponse) obj;
                        dismissPgDlg();
                        WaybillInfo waybillInfo = response.getData();
                        if (waybillInfo == null) {
                            showToast("子单下载主单数据为空(" + result + ")");
                            enableScan();
                            return;
                        }
                        //卸车串货提示开关启用
                        if (sharedPreferUtil.getUnLoadChuanHuoSwitch()) {
                            if (!Common.waybillRouteNoInRouteInfo(waybillInfo.getRouteCode(), mCurrentDeptCodes)) {
                                if (mTempResult != null && !mTempResult.equals(result)) {
                                    if (chuanhuoDialog != null) {
                                        chuanhuoDialog.dismiss();
                                        chuanhuoDialog = null;
                                    }
                                }
                                if (chuanhuoDialog == null) {
                                    Context mCurrContext = ActivityStack.getInstance().currentActivity();
                                    chuanhuoDialog = new MyDialog(mCurrContext);
                                }
                                mTempResult = result;
                                chuanhuoDialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                                chuanhuoDialog.setIcon(R.drawable.alert);
                                chuanhuoDialog.setTitle("系统提示");
                                chuanhuoDialog.setMessage(result + "运单目的站非本站，请注意！");
                                chuanhuoDialog.setPositiveClickListener("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        chuanhuoDialog = null;
                                    }
                                });
                                chuanhuoDialog.show();
                            }
                        }

                        //合并数据到内存，并插入当前条码到数据库
//                        merge(waybillInfo, result, null);

                        //查询库区
                        queryStorageCode(waybillInfo, result);
                    }
                });
    }

    /**
     * 查询库区
     */
    private void queryStorageCode(final WaybillInfo waybillInfo, final String result) {
        showPgDlg("查询库区中...");
        String temResult = result.substring(0, result.length() - 3);
        Map param = new HashMap();
        param.put("waybillNo", temResult);
        new NetRequest().setUrl(Constants.URL_GET_STORAGE_CODE)
                .setMethod(NetRequest.Method.GET)
                .setParams(param)
                .setResponsClazz(QueryStorageAreaResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        enableScan();
                        dismissPgDlg();
                        //合并数据到内存，并插入当前条码到数据库
                        merge(waybillInfo, result, null);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        enableScan();
                        dismissPgDlg();
                        QueryStorageAreaResponse response = (QueryStorageAreaResponse) obj;
                        if (response != null) {
                            QueryStorageAreaResponse.Data data = response.getData();
                            if (data != null) {
                                //合并数据到内存，并插入当前条码到数据库
                                merge(waybillInfo, result, data);
                            }
                        }
                    }
                });
    }

    /**
     * 合并数据到内存，并插入当前条码到数据库
     */
    private void merge(WaybillInfo waybillInfo, String result, QueryStorageAreaResponse.Data data) {

        //获取串货运单的上一站和配载任务的上一站相同的卸车任务
        UnloadTaskTable unloadTaskTable = null;
        UnloadTaskTable firstUcTask = null;
        UnloadTaskTable firstYmTask = null;
        String[] routeCodeSplit = new String[0];
        if (waybillInfo != null) {
            String routeCode = waybillInfo.getRouteCode();
            if (routeCode != null) {
                routeCodeSplit = routeCode.split(sharedPreferUtil.getDeptCode());
            }
        }
        List<UnloadTaskTable> list = mUnloadTaskDao.findData(task);
        if (list != null && !list.isEmpty()) {
            for (UnloadTaskTable entity : list) {
                String srcCode = entity.getSrcDeptCode();
                if (!entity.getStowageNo().startsWith("P")) {
                    //获取快递任务
                    if (firstUcTask == null) {
                        firstUcTask = entity;
                    }
                    if (UcWaybillValidate.validate(result)) {
                        if (routeCodeSplit.length > 0 && routeCodeSplit[0].startsWith(srcCode)) {
                            //获取上一站相同的卸车任务
                            unloadTaskTable = entity;
                            break;
                        }
                    }
                } else {
                    //获取快运任务
                    if (firstYmTask == null) {
                        firstYmTask = entity;
                    }
                    if (routeCodeSplit.length > 0 && routeCodeSplit[0].startsWith(srcCode)) {
                        //获取上一站相同的卸车任务
                        unloadTaskTable = entity;
                        break;
                    }
                }
            }
        }

        if (unloadTaskTable == null) {
            if (UcWaybillValidate.validate(result)) {
                unloadTaskTable = firstUcTask;
            } else {
                unloadTaskTable = firstYmTask;
            }

        }

        //构建数据
        QueryUnLoadDetailBillcode mQueryLoadDetailBillcode = new QueryUnLoadDetailBillcode();
        mQueryLoadDetailBillcode.setRemark("2");
        if (waybillInfo != null) {
            mQueryLoadDetailBillcode.setWaybillNo(waybillInfo.getWaybillNo() + "");
            mQueryLoadDetailBillcode.setSrcPiecesNum(waybillInfo.getQuantity());
            mQueryLoadDetailBillcode.setPiecesNum(waybillInfo.getNowInventory());
            mQueryLoadDetailBillcode.setWeight(waybillInfo.getRealWeight());
            mQueryLoadDetailBillcode.setVolume(waybillInfo.getVolume());
            mQueryLoadDetailBillcode.setChargedWeight(waybillInfo.getChargeableWeight());
            mQueryLoadDetailBillcode.setWaybillRoute(waybillInfo.getRouteCode());
        } else {
            try{
                mQueryLoadDetailBillcode.setWaybillNo(result.substring(0, 12));
            }catch (Exception e){

            }
        }
        mQueryLoadDetailBillcode.setPackageNo("");
        mQueryLoadDetailBillcode.setAreaCode("");
        mQueryLoadDetailBillcode.setBillType(1);
        if (unloadTaskTable != null) {
            mQueryLoadDetailBillcode.setTaskNo(unloadTaskTable.getTaskNo());
            mQueryLoadDetailBillcode.setStowageNo(unloadTaskTable.getStowageNo());
            mQueryLoadDetailBillcode.setRelationDeptCode(unloadTaskTable.getSrcDeptCode());
            mQueryLoadDetailBillcode.setRelationDeptName(unloadTaskTable.getSrcDeptName());
            mQueryLoadDetailBillcode.setRelationDeptType(unloadTaskTable.getRelationDeptType());
        } else {
            mQueryLoadDetailBillcode.setStowageNo(mUnloadTaskDao.getStowageNo(task).get(0));
        }
        mQueryLoadDetailBillcode.setCarNo(carNo);
        if (data != null) {
            if (data.getStorageCode() == null) {
                mQueryLoadDetailBillcode.setAreaCode("");
            } else {
                mQueryLoadDetailBillcode.setAreaCode(data.getStorageCode());
            }
            if (data.getNextDeptCode() == null) {
                mQueryLoadDetailBillcode.setNextDeptCode("");
            } else {
                mQueryLoadDetailBillcode.setNextDeptCode(data.getNextDeptCode());
            }
            if (data.getNextDeptName() == null) {
                mQueryLoadDetailBillcode.setNextDeptName("");
            } else {
                mQueryLoadDetailBillcode.setNextDeptName(data.getNextDeptName());
            }

        }

        List<QueryLoadDetailChildBillcode> childList = new ArrayList<>();
        //大票货
        if (result.endsWith("000")) {
            QueryLoadDetailChildBillcode mQueryLoadDetailChildBillcode = new QueryLoadDetailChildBillcode();
            mQueryLoadDetailChildBillcode.setFlag(1);
            mQueryLoadDetailChildBillcode.setChildWaybillNo(result);
            childList.add(mQueryLoadDetailChildBillcode);
            mQueryLoadDetailBillcode.setBigTicket(true);
        } else {
            if (waybillInfo != null) {
                for (int i = 0; i < waybillInfo.getQuantity(); i++) {
                    String childWaybillNo = waybillInfo.getWaybillNo() + String.format("%03d", i + 1);
                    QueryLoadDetailChildBillcode mQueryLoadDetailChildBillcode = new QueryLoadDetailChildBillcode();
                    if (result.equals(childWaybillNo)) {
                        mQueryLoadDetailChildBillcode.setFlag(1);
                    } else {
                        mQueryLoadDetailChildBillcode.setFlag(0);
                    }
                    mQueryLoadDetailChildBillcode.setChildWaybillNo(childWaybillNo);
                    childList.add(mQueryLoadDetailChildBillcode);
                }
            } else {
                QueryLoadDetailChildBillcode mQueryLoadDetailChildBillcode = new QueryLoadDetailChildBillcode();
                mQueryLoadDetailChildBillcode.setFlag(1);
                mQueryLoadDetailChildBillcode.setChildWaybillNo(result);
                childList.add(mQueryLoadDetailChildBillcode);
            }
        }
        mQueryLoadDetailBillcode.setChildList(childList);

        int goodsPriority = 0;
        if (mQueryLoadDetailBillcode.getGoodsPriority() != null) {
            goodsPriority = Integer.parseInt(mQueryLoadDetailBillcode.getGoodsPriority());
        }
        //插入表
        UnloadScanTable mUnloadScanTable =
                new UnloadScanTable(task, mQueryLoadDetailBillcode.getWaybillNo(), result, mQueryLoadDetailBillcode.getPackageNo(),
                        mQueryLoadDetailBillcode.getStowageNo(), operTypeCode, inputType, mQueryLoadDetailBillcode.getRemark(),
                        mQueryLoadDetailBillcode.getAreaCode(), SharedPreferUtil.getInstance().getValue(Common.USER_CODE),
                        SharedPreferUtil.getInstance().getValue(Common.USER_NAME), Constants.GetSysTime(), Constants.GetScanTime(),
                        SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE), SysInfo.getInstance().getImei(),
                        mQueryLoadDetailBillcode.getCarNo(), 0, goodsPriority, mQueryLoadDetailBillcode.getProductType(),
                        //waybillType：1-快运，2-快递
                        joinWrokNum, joinUserName, deptType, mPalletTaskNo, platformNo, sharedPreferUtil.getValue(Common.MOVE_IN_PLACE_CODE), 1,
                        mQueryLoadDetailBillcode.getTaskNo(), null, yiXingJian.isChecked() ? 1 : 0);
        mUnloadScanTable.setRelationDeptCode(mQueryLoadDetailBillcode.getRelationDeptCode());
        mUnloadScanTable.setRelationDeptName(mQueryLoadDetailBillcode.getRelationDeptName());
        mUnloadScanTable.setRelationDeptType(mQueryLoadDetailBillcode.getRelationDeptType());
        try {
            if (mUnloadScanTableDao.insert(mUnloadScanTable) <= 0) {
                SoundVibratorManager.playSound(2);
                Toast.makeText(UnloadScanActivity.this, "插入数据库失败！", Toast.LENGTH_LONG).show();
                return;
            }
        } catch (SQLException e) {
            showToast("强扫卸车数据保存异常：" + e.toString());
            return;
        }
        //更新显示信息
        scanedjian.setText((Integer.parseInt(scanedjian.getText().toString()) + 1) + "");
        //强扫票数肯定加1
        scanedpiao.setText((Integer.parseInt(scanedpiao.getText().toString()) + 1) + "");

        //未扫描数+1
        addUnloadCount();
        SoundVibratorManager.playSound(1);
        unloadDataEntityList.add(0, mQueryLoadDetailBillcode);
        /**添加托盘绑定数据*/
        addPalletBindData(result, mQueryLoadDetailBillcode, 1);
        //根据复选框类型显示运单列表
        showInfosByCheckBox();
    }

    private synchronized void setUnloadCount(String count) {
        //设置未上传数
        num.setText(count);
    }

    private synchronized void addUnloadCount() {
        //设置未上传数
        num.setText((Integer.parseInt(num.getText().toString()) + 1) + "");
    }

    private synchronized void decreaseUnloadCount(int decreaseCount) {
        //更新未上传数
        int count = Integer.parseInt(num.getText().toString()) - decreaseCount;
        if (count < 0) {
            num.setText("0");
            count = 0;
        } else {
            num.setText(count + "");
        }
        EventBus.getDefault().post(new CountEvent(count));
    }

    /**
     * 是否在上传数据
     */
    private boolean isDoing = false;
    private List<UnloadScanTable> mTempUnloadScanTableList;
    /**
     * 异常运单处理标志
     */
    private boolean exceptionWBHandle = false;
    private List<UnloadScanTable> uploadList;

    /**
     * 每次扫描未上传数据
     */
    private void upload(List<UnloadScanTable> list) {
        if (list == null) {
            //查询未上传数据
            list = mUnloadScanTableDao.getUnUpload(task, operTypeCode);
        }
        if (list != null && !list.isEmpty()) {
            //取list中前10条数据
            uploadList = list;
            if (list.size() >= Common.SCAN_UPLOAD_NUM) {
                list = list.subList(0, Common.SCAN_UPLOAD_NUM);
            }

            for (UnloadScanTable item : list) {
                item.setIsUpload(1);
            }
            //实例化上传类
            ScanLoadUploadRequest mScanLoadUploadRequest = new ScanLoadUploadRequest();
            mScanLoadUploadRequest.setRecords(list);
            isDoing = true;

            final List<UnloadScanTable> finalList = list;
            new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                    .setUrl(Constants.UPLOAD_DATA_POST_URL)
                    .setRequestObject(mScanLoadUploadRequest)
                    .setResponsClazz(QueryUnloadDetailResponse.class)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            LogUtil.e(msg);
                        }

                        @Override
                        public void onError(final String msg, final Object obj) {
                            isDoing = false;
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        isDoing = false;
                                        if (finalList.size() == 1) {
                                            if (isClickSubmit) {
                                                LoadUtil.updateErrorWaybillStatus(finalList, mUnloadScanTableDao);
                                                upload(null);
                                            } else if (!msg.equals(Constants.PLEASE_CHECK_NET)) {
                                                showError(msg, finalList);
                                            }
                                        } else if (finalList.size() > 1) {
                                            if (exceptionWBHandle && msg.contains("运单已签收不能装车")) {
                                                if (isClickSubmit) {
                                                    LoadUtil.updateErrorWaybillStatus(finalList, mUnloadScanTableDao);
                                                    upload(null);
                                                } else if (!msg.equals(Constants.PLEASE_CHECK_NET)) {
                                                    showError(msg, finalList);
                                                }
                                            } else {
                                                //运单上传失败后，遍历list单个上传，找出有异常的运单提示用户删除后，后面的运单批量上传
                                                exceptionWBHandle = true;
                                                mTempUnloadScanTableList = finalList;
                                                List<UnloadScanTable> tempList = new ArrayList<>();
                                                if (msg.contains("运单已签收不能装车")) {
                                                    String waybillNo = finalList.get(0).getWaybillNo();
                                                    for (UnloadScanTable item : finalList) {
                                                        if (waybillNo.equals(item.getWaybillNo())) {
                                                            tempList.add(item);
                                                        }
                                                    }
                                                } else {
                                                    tempList.add(finalList.get(0));
                                                }
                                                upload(tempList);
                                            }
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            isDoing = false;
                            try {
                                //更新数据库状态
                                for (UnloadScanTable item : finalList) {
                                    mUnloadScanTableDao.update(item);
                                }
                                //减少未上传数据
                                decreaseUnloadCount(finalList.size());
                            } catch (Exception e) {
                                LogUtil.e(e.toString());
                            }

                            if (exceptionWBHandle) {
                                //遍历异常运单中的正常运单
                                Iterator<UnloadScanTable> it = mTempUnloadScanTableList.iterator();
                                while (it.hasNext()) {
                                    UnloadScanTable item = it.next();
                                    for (UnloadScanTable unloadScanTable : finalList) {
                                        if (item.getWaybillNo().equals(unloadScanTable.getWaybillNo())) {
                                            it.remove();
                                            break;
                                        }
                                    }
                                }
                                if (!mTempUnloadScanTableList.isEmpty()) {
                                    List<UnloadScanTable> list = new ArrayList<>();
                                    list.add(mTempUnloadScanTableList.get(0));
                                    upload(list);
                                }
                            } else {
                                synchronized (uploadList) {
                                    Iterator<UnloadScanTable> it = uploadList.iterator();
                                    int count = 0;
                                    while (it.hasNext()) {
                                        it.next();
                                        if (count < Common.SCAN_UPLOAD_NUM) {
                                            it.remove();
                                        }
                                        count++;
                                    }
                                    upload(uploadList);
                                    return;
                                }
                            }

                            if (isClickSubmit) {
                                isClickSubmit = false;
                                uploadTask();
                            }
                        }
                    });
        } else {
            isDoing = false;
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    LoadUtil.setUnloadCount(num, mPlanTaskList, mUnloadScanTableDao, operTypeCode);
                    if (isClickSubmit) {
                        isClickSubmit = false;
                        uploadTask();
                    }
                }
            });
        }
    }

    /**
     * 显示错误信息
     */
    private void showError(String error, final List<UnloadScanTable> list) {
        setScannerEnabled(false);
        if (isFinishing()) {
            return;
        }
        Context currentContext = ActivityStack.getInstance().currentActivity();
        MyDialog mErrorDialog = MyDialog.getInstance(currentContext);
        mErrorDialog.setIcon(R.drawable.alert);

        if (error.contains("9601")) {
            String errorWaybill = error.substring(error.indexOf("[") + 1, error.indexOf("]"));
            error = "同行交接时，没有交接此子单号：" + errorWaybill;
            mErrorDialog.setMessage(error + "，是否放弃该条码扫描？");
        } else {
            mErrorDialog.setMessage("上传报错:【" + error + "】，是否放弃该条码扫描？");
        }

        mErrorDialog.setPositiveClickListener("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                MyDialog.setNull();
                setScannerEnabled(true);
                isDoing = false;
                try {
                    DbHelper dbHelper = mUnloadScanTableDao.getDbHelper();
                    if (dbHelper != null && dbHelper.isOpen()) {
                        mUnloadScanTableDao.delete(list);
                    }
                } catch (SQLException e) {
                    LogUtil.e(e.toString());
                }
                //设置内存中的数据为未扫描
                for (UnloadScanTable item : list) {
                    //遍历服务器返回数据集合
                    for (QueryUnLoadDetailBillcode billDto : unloadDataEntityList) {
                        if (item.getWaybillNo().equals(billDto.getWaybillNo())) {
                            if (billDto.getChildList() != null) {
                                Iterator<QueryLoadDetailChildBillcode> it = billDto.getChildList().iterator();
                                while (it.hasNext()) {
                                    QueryLoadDetailChildBillcode child = it.next();
                                    if (child.getChildWaybillNo().equals(item.getChildWaybillNo())) {
                                        child.setFlag(0);
                                        it.remove();
                                    }
                                }
                            }
                            billDto.setUcScan(false);
                        }
                    }
                }

                //清除托盘绑定中的运单
                if (mPalletBindList != null) {
                    for (UnloadScanTable item : list) {
                        for (QueryUnLoadDetailBillcode detail : mPalletBindList) {
                            if (item.getWaybillNo().equals(detail.getWaybillNo())) {
                                if (detail.getChildList() != null) {
                                    Iterator<QueryLoadDetailChildBillcode> it = detail.getChildList().iterator();
                                    while (it.hasNext()) {
                                        QueryLoadDetailChildBillcode child = it.next();
                                        if (child.getChildWaybillNo().equals(item.getChildWaybillNo())) {
                                            it.remove();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //发送消息给托盘托盘绑定界面，通知刷新列表
                sendHandlerToPalletBindActivity();

                //根据复选框类型显示运单列表
                showInfosByCheckBox();
                spiltList(unloadDataEntityList);

                //处理异常运单
                if (exceptionWBHandle) {
                    exceptionWBHandle = false;
                    //内存中删除异常的运单
                    mTempUnloadScanTableList.removeAll(list);
                    upload(null);
                }
            }
        });
        mErrorDialog.setCancelable(false);
        mErrorDialog.setNegativeClickListener(R.drawable.btn_cancel_selector, "否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                MyDialog.setNull();
                isDoing = false;
                setScannerEnabled(true);
            }
        });
        mErrorDialog.setCanceledOnTouchOutside(false);
        try {
            mErrorDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public UnloadScanActivity() {
        super(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unload_scan);
        initView();
        initValue();
        setHandler();

        //注册事件
        EventBus.getDefault().register(this);

        ThreadPoolUtils.execute(new UploadRunnable());
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.getId() == R.id.cb_palletBind) {
            //托盘绑定
            if (isChecked) {
                mPalletTaskNo = Constants.getPalletTaskNo();
                btnPalletBind.setEnabled(true);
            } else {
                //托盘list中有数据不可取消勾选
                if (mPalletBindList != null && !mPalletBindList.isEmpty()) {
                    buttonView.setChecked(true);
                    MyDialog.showAlertDialog(UnloadScanActivity.this, "提示", "托盘内有未提交完成的数据，无法取消勾选！", "确定");
                    return;
                }
                mPalletTaskNo = null;
                if (mPalletBindList != null) mPalletBindList.clear();
                btnPalletBind.setEnabled(false);
            }
            //保存勾选状态
            LoadUnLoadGroupTable loadUnLoadGroupTable = mLoadGroupDao.getData();
            if (loadUnLoadGroupTable != null) {
                loadUnLoadGroupTable.setPalletBindCheck(isChecked);
                try {
                    mLoadGroupDao.update(loadUnLoadGroupTable);
                } catch (SQLException e) {
                    LogUtil.e(e.toString());
                }
            }
        } else if (buttonView.getId() == R.id.cb_chao_chang_jian) {
            //超长件
            HiddenAnimUtils.newInstance(this, rgChaoChangJian, null, 30).toggle();
            if (isChecked) {
                if (rbChaoChangJian1.isChecked()) {
                    chaoChangJian = 1;
                } else if (rbChaoChangJian2.isChecked()) {
                    chaoChangJian = 2;
                } else if (rbChaoChangJian3.isChecked()) {
                    chaoChangJian = 3;
                } else {
                    chaoChangJian = null;
                }
            } else {
                chaoChangJian = null;
            }
        } else {
            if (!cbKuaiYun.isChecked() && !cbKuaiDi.isChecked()) {
                showToast("至少保留一项！");
                buttonView.setChecked(true);
                return;
            }
            //根据复选框类型显示运单列表
            showInfosByCheckBox();
        }
    }

    /**
     * 根据复选框类型显示运单列表
     */
    private void showInfosByCheckBox() {
        if (cbKuaiYun.isChecked() && cbKuaiDi.isChecked()) {
            //显示所有运单
            showInfosByType(0);
        } else if (cbKuaiYun.isChecked()) {
            //显示快运运单
            showInfosByType(1);
        } else {
            //显示快递运单
            showInfosByType(2);
        }
    }

    /**
     * 根据type显示快运或者快递的运单
     *
     * @param type 0-所有，1-快运，2-快递
     */
    private void showInfosByType(int type) {
        if (unloadDataEntityList != null) {
            if (type == 0) {
                loadListAdapter(unloadDataEntityList);
                return;
            }
            List<QueryUnLoadDetailBillcode> tempInfo = new ArrayList<>();
            for (QueryUnLoadDetailBillcode item : unloadDataEntityList) {
                if (type == 1 && !UcWaybillValidate.validate(item.getWaybillNo())) {
                    //快运运单
                    tempInfo.add(item);
                } else if (type == 2 && UcWaybillValidate.validate(item.getWaybillNo())) {
                    //快递运单
                    tempInfo.add(item);
                }
            }
            loadListAdapter(tempInfo);
        }
    }

    /**
     * 加载list适配器
     *
     * @param list 运单列表集合
     */
    private void loadListAdapter(List<QueryUnLoadDetailBillcode> list) {
        loadAdapter(list);
        //更新汇总数据
        collectData(list);
    }

    private void loadAdapter(List<QueryUnLoadDetailBillcode> list) {
        if (adapter == null) {
            adapter = new UnLoadAdapter(UnloadScanActivity.this, list, listHead);
            listView.setAdapter(adapter);
        } else {
            //刷新界面
            adapter.setDataList(list);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 异步排序
     */
    private void asyncSort(final List<QueryUnLoadDetailBillcode> list) {
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                sortList(list);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                loadAdapter(list);
            }

            @Override
            public void onError(Throwable throwable) {
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.rb_chao_chang_1) {
            chaoChangJian = 1;
        } else if (checkedId == R.id.rb_chao_chang_2) {
            chaoChangJian = 2;
        } else if (checkedId == R.id.rb_chao_chang_3) {
            chaoChangJian = 3;
        } else {
            chaoChangJian = null;
        }
    }

    //上传数据的线程
    private class UploadRunnable implements Runnable {
        @Override
        public void run() {
            while (!isExit) {
                try {
                    //是否正在上传数据
                    if (!isDoing) {
                        //上传数据
                        upload(null);
                    }

                    Thread.sleep(5000);
                } catch (Exception e) {
                    LogUtil.e(e.toString());
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        //获取装卸组信息
        getGroupInfo();

        //判断卸车倒计时已经开始扫描则继续倒计时
        reStartCountDown();

        //第一次进入加载数据，后面直接刷新数据
        if (isfirst) {
            loadData(false);
        }
        setUnloadCount(mUnloadScanTableDao.queryCount("isUpload", 0, 2) + "");
        isfirst = false;
        // 间隔300秒(五分钟),自动校验时间
        checkTimeHandler.postDelayed(runnable, loadTime);
    }

    /**
     * 重新开始卸车倒计时
     */
    private void reStartCountDown() {
        if (isScan) {
            return;
        }
        LoadUnloadTimeTable timeTable =
                loadUnloadTimeTableDao.getData(sharedPreferUtil.getValue(Common.USER_CODE), sharedPreferUtil.getCompanyCode(), task);
        if (timeTable != null && timeTable.getIsScan() == 1) {
            isScan = true;
            //当前时间
            String currentDate = DateHelper.getDateTimeFormate(new Date());
            //卸车完成时间点
            String finishTimePoint = timeTable.getUnloadFinishTimePoint();
            try {
                //当前时间
                Date d1 = DateHelper.timeFormat.parse(currentDate);
                //卸车完成时间点
                Date d2 = DateHelper.timeFormat.parse(finishTimePoint);
                //差值是微秒级别
                long diff = d2.getTime() - d1.getTime();
                if (diff <= 0) {
                    tvUnloadTime.setText("00:00");
                    tvUnloadTime.setTextColor(getResources().getColor(R.color.red));
                } else {
                    long days = diff / (1000 * 60 * 60 * 24);
                    long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
                    long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
                    long seconds = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60) - minutes * (1000 * 60)) / (1000);
                    //剩余分钟
                    long remainMinutes = (days * 24 * 60) + (hours * 60) + minutes;
                    startCountDown(remainMinutes, (int) seconds);
                }
            } catch (Exception e) {
                LogUtil.e(e.toString());
            }
        }
    }

    private int zpiao = 0;
    private int zjian = 0;
    private int spiao = 0;
    private int sjian = 0;

    /**
     * 更新汇总数据
     */
    private void collectData(final List<QueryUnLoadDetailBillcode> list) {
        zpiao = 0;
        zjian = 0;
        spiao = 0;
        sjian = 0;
        mPalletBindNum = 0;
        mBindPiaoNum = 0;

        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                //遍历服务器返回数据集合
                for (QueryUnLoadDetailBillcode billDto : list) {
                    zpiao++;
                    if (billDto.getSrcPiecesNum() == null) {
                        billDto.setSrcPiecesNum(0);
                    }
                    if (billDto.getPiecesNum() == null) {
                        billDto.setPiecesNum(0);
                    } else {
                        zjian += billDto.getPiecesNum();
                    }

                    int count = billDto.getScanCount();
                    //统计已扫描的数量
                    if (count > 0) {
                        if ("2".equals(billDto.getWaybillType())) {
                            spiao++;
                            sjian += billDto.getSrcPiecesNum();
                        } else {
                            spiao++;
                            sjian += count;
                        }
                    }
                    mPalletBindNum += billDto.getForkLiftNum();
                    if (billDto.getForkLiftNum() > 0) {
                        mBindPiaoNum++;
                    }
                }
                spiltList(unloadDataEntityList);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                //设置总票/件，实操票/件
                totlepiao.setText(zpiao + "");
                totlejian.setText(zjian + "");
                scanedpiao.setText(spiao + "");
                scanedjian.setText(sjian + "");
                //托盘数
                tvPalletBindNo.setText(mPalletBindNum + "");
                tvBindPiaoNo.setText(mBindPiaoNum + "");

                asyncSort(list);
            }

            @Override
            public void onError(Throwable throwable) {
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    @Override
    public String getPageName() {
        return "卸车扫描";
    }

    public void initView() {
        ((TextView) findViewById(R.id.title)).setText("卸车扫描");
        num = findViewById(R.id.num);
        nextStation = findViewById(R.id.next_station);

        listView = findViewById(R.id.unload_task_listview);
        listView.setOnTouchListener(new ListViewAndHeadViewTouchLinstener());
        findViewById(R.id.unload_scan_back).setOnClickListener(this);
        findViewById(R.id.unload_upload).setOnClickListener(this);
        findViewById(R.id.unload_refresh).setOnClickListener(this);
        btnAdd = findViewById(R.id.unload_btn_add);
        btnAdd.setOnClickListener(this);
        btnLoadUnloadGroup = findViewById(R.id.btn_modifyLoadUnloadPeople);
        btnLoadUnloadGroup.setOnClickListener(this);
        totlepiao = findViewById(R.id.unload_totle_piao);
        totlejian = findViewById(R.id.unload_totle_jian);
        scanedpiao = findViewById(R.id.unload_real_piao);
        scanedjian = findViewById(R.id.unload_real_jian);
        tvShowDesc = findViewById(R.id.tv_showDesc);
        cbPalletBind = findViewById(R.id.cb_palletBind);
        cbPalletBind.setOnCheckedChangeListener(this);
        cbChaoChangJian = findViewById(R.id.cb_chao_chang_jian);
        cbChaoChangJian.setOnCheckedChangeListener(this);
        rgChaoChangJian = findViewById(R.id.rg_chao_chang_jian);
        rgChaoChangJian.setOnCheckedChangeListener(this);
        rbChaoChangJian1 = findViewById(R.id.rb_chao_chang_1);
        rbChaoChangJian2 = findViewById(R.id.rb_chao_chang_2);
        rbChaoChangJian3 = findViewById(R.id.rb_chao_chang_3);
        btnPalletBind = findViewById(R.id.btn_palletBind);
        btnPalletBind.setOnClickListener(this);
        tvPalletBindNo = findViewById(R.id.tv_palletBindNo);
        tvBindPiaoNo = findViewById(R.id.tv_bindPiaoNo);
        listHead = findViewById(R.id.listHead);
        listHead.setFocusable(true);
        listHead.setClickable(true);
        listHead.setOnTouchListener(new ListViewAndHeadViewTouchLinstener());
        llPalletBindNum = findViewById(R.id.ll_pallet_bind_num);
        ivDownLayout = findViewById(R.id.iv_down_layout);
        ivDownLayout.setOnClickListener(this);
        llFunctionBtn = findViewById(R.id.ll_function_btn);
        llFunctionBtn.setVisibility(View.GONE);
        tvUnloadTime = findViewById(R.id.tv_unloadTime);
        cbKuaiYun = findViewById(R.id.cb_kuai_yun);
        cbKuaiYun.setOnCheckedChangeListener(this);
        cbKuaiDi = findViewById(R.id.cb_kuai_di);
        cbKuaiDi.setOnCheckedChangeListener(this);
        yiXingJian = findViewById(R.id.cb_yixing_jian);
    }

    public void initValue() {
        //对话框初始化
        MyDialog.setNull();
        //新手引导提示
        Common.showIntro(this, ivDownLayout, "点击可显示隐藏功能", this.getPageName());

        cbKuaiYun.setChecked(true);
        cbKuaiDi.setChecked(true);

        loadUnloadTimeTableDao = new LoadUnloadTimeTableDao();
        mJieLiuJianTableDao = new JieLiuJianTableDao();
        mUnloadTaskDao = new UnloadTaskTableDao();
        mPalletBindList = new ArrayList<>();
        mUnloadScanTableDao = new UnloadScanTableDao();
        mDepartDao = new DepartmentTableDao();
        mLoadGroupDao = new LoadUnloadGroupTableDao();

        //融合：卸车任务集合
        mPlanTaskList = (List<CarPlanTaskEntity>) getIntent().getSerializableExtra("carPlaneTasks");

        carNo = getIntent().getStringExtra("carNo");
        task = getIntent().getStringExtra("task");
        //上一站名称
        deptCode = getIntent().getStringExtra("deptCode");
        //卸车当前站（下一站）
        mCurrentDeptCodes = (List<String>) getIntent().getSerializableExtra("currentDeptCodes");

        String srcDeptName = "";
        if (mPlanTaskList != null) {
            for (CarPlanTaskEntity planTask : mPlanTaskList) {
                if (planTask.getLoadTasks() != null) {
                    for (LoadBillTaskEntity unloadTask : planTask.getLoadTasks()) {
                        if (unloadTask.getSrcDeptName() != null) {
                            srcDeptName += unloadTask.getSrcDeptName() + " ";
                        } else {
                            DepartmentTable departTable = mDepartDao.queryDeptByDeptCode(unloadTask.getSrcDeptCode());
                            if (departTable != null) {
                                srcDeptName += departTable.getDeptName() + " ";
                            }
                        }
                    }
                }
            }
        }

        //卸车上一站
        nextStation.setText(srcDeptName);
        //获取装卸组信息
        getGroupInfo();

        //分拨使用蓝牙称
        if (deptType == 5 || deptType == 6) {
            BlueToothUtil.INSTANCE.setListener(this);
            //快递蓝牙称连接
            connectBlue();
        }

        if (!cbChaoChangJian.isChecked()) {
            rgChaoChangJian.setVisibility(View.GONE);
        }

        //查询上传扫描条数
        Common.queryDictScanUploadNum();

        //查询当前分拨是否为快递中心到件，用于中心到件预付款提醒
        ThreadPoolUtils.execute(new queryZXDJRunnable());
    }

    /**
     * 快递蓝牙称连接
     */
    private void connectBlue() {
        if (BluetoothAdapter.getDefaultAdapter() != null && BluetoothAdapter.getDefaultAdapter().isEnabled()) {
            if (TextUtils.isEmpty(Sp_net_Util.getInstance().get("blueTooth"))) {
                AlertDialogUtils.getInstance().initBlueToothSettingDialog(this);
                return;
            }
            AlertDialogUtils.getInstance().initBlueToothSettingDialog(this, "是否连接蓝牙，地址是" + Sp_net_Util.getInstance().get("blueTooth")).setCallBackListener(new AlertDialogUtils.ClickOkCallBackListener() {
                @Override
                public void clickOk(String address) {
                    BlueToothUtil.INSTANCE.initBlue();
                }
            });
        }
    }

    /**
     * 查询中心到件
     */
    private class queryZXDJRunnable implements Runnable {
        @Override
        public void run() {
            if (deptType == 5 || deptType == 6) {
                List<UnloadTaskTable> list = mUnloadTaskDao.findData(task);
                if (list != null) {
                    zxdjTasks = new ArrayList<>();
                    for (UnloadTaskTable taskTable : list) {
                        if (!taskTable.getStowageNo().startsWith("P")) {
                            UCDeptTable ucDeptTable = new UCDeptTableDao().findDataByBaseOrgCode(taskTable.getSrcDeptCode());
                            if (ucDeptTable != null && ucDeptTable.getOrgType() == 30) {
                                //当前登录为分拨，且快递上一站是网点，则为中心到件
                                zxdjTasks.add(taskTable);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取装卸组信息
     */
    private void getGroupInfo() {
        //部门类型
        deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
        LoadUnLoadGroupTable loadUnLoadGroupTable = mLoadGroupDao.getData();
        if (loadUnLoadGroupTable != null) {
            cbPalletBind.setChecked(loadUnLoadGroupTable.isPalletBindCheck());
        }
        if (cbPalletBind.isChecked()) {
            if (mPalletTaskNo == null) {
                mPalletTaskNo = Constants.getPalletTaskNo();
            } else {
                String oldForliftNo = sharedPreferUtil.getValue(Common.OLD_FORLIFT_NO);
                if (mPalletTaskNo.equals(oldForliftNo)) {
                    //托盘号不能与旧的托盘号相同，相同则重新生成一个新的托盘任务号
                    mPalletTaskNo = Constants.getPalletTaskNo();
                }
            }
            btnPalletBind.setEnabled(true);
        } else {
            mPalletTaskNo = null;
            btnPalletBind.setEnabled(false);
        }
        if (deptType == 5 || deptType == 6) {
            //分拨才使用托盘绑定功能
            cbPalletBind.setVisibility(View.VISIBLE);
            btnPalletBind.setVisibility(View.VISIBLE);
            llPalletBindNum.setVisibility(View.VISIBLE);
            //分拨才使用装卸组功能
            tvShowDesc.setVisibility(View.GONE);
            btnLoadUnloadGroup.setVisibility(View.VISIBLE);
            if (loadUnLoadGroupTable != null) {
                //获取月台好
                platformNo = loadUnLoadGroupTable.getPlatform();
            }
            joinWrokNum = getIntent().getStringExtra("joinWrokNum");
            joinUserName = getIntent().getStringExtra("joinUserName");
            if (joinWrokNum == null || joinUserName != null) {
                LoadUnLoadGroupTable groupTable = mLoadGroupDao.getData();
                if (groupTable != null) {
                    joinWrokNum = groupTable.getUserCodes();
                    joinUserName = groupTable.getUserNames();
                }
            }
            if (joinUserName == null || joinUserName.equals("")) {
                joinUserName = joinWrokNum;
            }
            if (joinWrokNum == null || joinUserName == null) {
                if (loadUnLoadGroupTable != null) {
                    joinWrokNum = loadUnLoadGroupTable.getUserCodes();
                    joinUserName = loadUnLoadGroupTable.getUserNames();
                    if (joinUserName == null || joinUserName.equals("")) {
                        joinUserName = joinWrokNum;
                    }
                } else {
                    joinWrokNum = sharedPreferUtil.getValue(Common.USER_CODE);
                    joinUserName = sharedPreferUtil.getValue(Common.USER_NAME);
                    if (joinUserName == null || joinUserName.equals("")) {
                        joinUserName = joinWrokNum;
                    }
                }
            }
        } else {
            //网点屏蔽托盘功能
            cbPalletBind.setVisibility(View.GONE);
            btnPalletBind.setVisibility(View.GONE);
            llPalletBindNum.setVisibility(View.GONE);
            //网点屏蔽装卸组功能
            tvShowDesc.setVisibility(View.VISIBLE);
            btnLoadUnloadGroup.setVisibility(View.GONE);
            joinWrokNum = sharedPreferUtil.getValue(Common.USER_CODE);
            joinUserName = sharedPreferUtil.getValue(Common.USER_NAME);
            if (joinUserName == null || joinUserName.equals("")) {
                joinUserName = joinWrokNum;
            }
        }
        //自动检测没有省区的工号，自动添加上去
        String compCode = sharedPreferUtil.getCompanyCode();
        if (compCode == null || "".equals(compCode)) {
            showToast("企业编码为空！");
        }
        String[] userCodes = joinWrokNum.split(",");
        for (int i = 0; i < userCodes.length; i++) {
            String userCode = userCodes[i];
            if (!userCode.contains("@")) {
                userCodes[i] = userCode + "@" + compCode;
            }
        }
        StringBuilder tempUserCodes = new StringBuilder();
        for (String userCode : userCodes) {
            tempUserCodes.append(userCode + ",");
        }
        joinWrokNum = tempUserCodes.substring(0, tempUserCodes.length() - 1);
    }

    /**
     * 根据卸车配载单号下载卸车数据
     */
    private void loadData(final boolean isSubmit) {
        //关闭扫描
        setScannerEnabled(false);
        showPgDlg("正在加载...");

        QueryUnloadDetailRequest mQueryUnloadDetailRequest = new QueryUnloadDetailRequest();
        //查询快运配载单号
        stowageNos = mUnloadTaskDao.getStowageNo(task);
        mQueryUnloadDetailRequest.setStowageNos(stowageNos);
        //查询快递任务号
        List<UnloadUcTaskNoTable> ucTaskNoTableList = new UnloadUcTaskNoTableDao().getUcTaskNos(task);
        mUcTaskNoVoList = new ArrayList<>();
        if (ucTaskNoTableList != null) {
            for (UnloadUcTaskNoTable item : ucTaskNoTableList) {
                mUcTaskNoVoList.add(new UcTaskNoVo(item.getTaskNo(), item.getVheLineType()));
            }
            mQueryUnloadDetailRequest.setUcTaskNos(mUcTaskNoVoList);
        }

        //判断是否只有优速卸车任务，或者只有壹米快运任务
        isUcOneTask = true;
        isYmOneTask = true;
        for (String item : stowageNos) {
            if (!item.startsWith("P")) {
                isYmOneTask = false;
            } else {
                isUcOneTask = false;
            }
        }

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setRequestObject(mQueryUnloadDetailRequest)
                .setUrl(Constants.URL_GET_UNLOAD_SCAN_DATA)
                .setResponsClazz(QueryUnloadDetailResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        unloadDataEntityList = new ArrayList<>();

                        //根据复选框类型显示运单列表
                        showInfosByCheckBox();
                        spiltList(unloadDataEntityList);

                        dismissPgDlg();
                        //开启扫描
                        setScannerEnabled(true);
                        SoundVibratorManager.playSound(2);
                        showToast("加载数据失败：" + msg);
                        LogUtil.e("加载数据失败：" + msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryUnloadDetailResponse response = (QueryUnloadDetailResponse) obj;
                        if (response != null) {
                            unloadDataEntityList.clear();
                            unloadDataEntityList.addAll(response.getData());

                            List<UnloadTaskTable> taskTableList = mUnloadTaskDao.findData(task);
                            for (UnloadTaskTable taskTable : taskTableList) {
                                for (QueryUnLoadDetailBillcode unloadDetail : unloadDataEntityList) {
                                    if (taskTable.getStowageNo().equals(unloadDetail.getStowageNo())) {
                                        unloadDetail.setRelationDeptCode(taskTable.getSrcDeptCode());
                                        unloadDetail.setRelationDeptName(taskTable.getSrcDeptName());
                                        unloadDetail.setRelationDeptType(taskTable.getRelationDeptType());
                                        unloadDetail.setTaskNo(taskTable.getTaskNo());
                                    }
                                }
                            }

                            insertData(isSubmit);
                        }
                    }
                });
    }

    /**
     * 合并相同运单号
     */
    private List<QueryUnLoadDetailBillcode> merageTheSameWayBillNos(List<QueryUnLoadDetailBillcode> unloadDataList) {
        final List<QueryUnLoadDetailBillcode> mergeDataList = new ArrayList<>();
        Integer piecesNum = 0;
        for (QueryUnLoadDetailBillcode entity : unloadDataList) {
            //交件件数
            piecesNum = 0;
            QueryUnLoadDetailBillcode queryUnLoadDetailBillcode = new QueryUnLoadDetailBillcode();
            Set<QueryLoadDetailChildBillcode> childBillcodes=null;
            if (entity.getChildList() != null) {
                childBillcodes = new HashSet<>();
                for (QueryLoadDetailChildBillcode childEntity : entity.getChildList()) {
                    //设置子单合并前对应的配载单号
                    childEntity.setStowageNo(entity.getStowageNo());
                    childBillcodes.add(childEntity);
                }
            }

            piecesNum += entity.getPiecesNum();
            //交接件数不能大于开单件数
            if (piecesNum > entity.getSrcPiecesNum()) {
                piecesNum = entity.getSrcPiecesNum();
            }
            queryUnLoadDetailBillcode = entity;
            //设置交件件数
            queryUnLoadDetailBillcode.setPiecesNum(piecesNum);
            //设置子单
            if (childBillcodes!=null){
                queryUnLoadDetailBillcode.setChildList(new ArrayList<QueryLoadDetailChildBillcode>(childBillcodes));
            }
            mergeDataList.add(queryUnLoadDetailBillcode);
        }
        return mergeDataList;
    }

    /**
     * 将数据库数据插入到列表中
     */
    protected void insertData(final boolean isSubmit) {
        showPgDlg("本地数据处理中...");
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                chargedWeight = 0;
                //在加载本地数据前，合并相同运单，防止丢失已扫描的本地数据
                if (unloadDataEntityList == null) {
                    unloadDataEntityList = new ArrayList<>();
                }

                /*****合并相同运单号*****/
                unloadDataEntityList = merageTheSameWayBillNos(unloadDataEntityList);
                /*****合并相同运单号*****/

                if (unloadDataEntityList.isEmpty()) {
                    //查询快递任务的数据
                    List<String> stowageNos = mUnloadTaskDao.getStowageNo(task);
                    List<UnloadScanTable> scanTableList = mUnloadScanTableDao.getUcScanDataByTaskNo(stowageNos, 2);
                    for (UnloadScanTable item : scanTableList) {
                        QueryUnLoadDetailBillcode loadInfo = new QueryUnLoadDetailBillcode();
                        loadInfo.setWaybillNo(item.getWaybillNo());
                        loadInfo.setUcScan(true);
                        loadInfo.setSrcPiecesNum(1);
                        loadInfo.setWeight(item.getWeight());
                        if (item.getChargedWeight() != null) {
                            loadInfo.setChargedWeight(new BigDecimal(item.getChargedWeight()));
                        }
                        //设置优速子单
                        List<QueryLoadDetailChildBillcode> childBillcodeList = new ArrayList<>();
                        QueryLoadDetailChildBillcode childBillcode = new QueryLoadDetailChildBillcode();
                        childBillcode.setChildWaybillNo(item.getWaybillNo());
                        childBillcode.setFlag(1);
                        childBillcode.setStowageNo(item.getStowageNo());
                        childBillcodeList.add(childBillcode);
                        loadInfo.setChildList(childBillcodeList);
                        unloadDataEntityList.add(loadInfo);
                    }
                } else {
                    //遍历服务器返回数据集合
                    for (QueryUnLoadDetailBillcode billDto : unloadDataEntityList) {
                        chargedWeight += billDto.getChargedWeight().doubleValue();
                        //查询本地该任务中已经扫描的数据
                        List<UnloadScanTable> expressLoadingEntities = mUnloadScanTableDao.getTaskWaybillNoData(2, billDto.getStowageNo(), billDto.getWaybillNo());
                        if (billDto.getChildList() != null
                                && !billDto.getChildList().isEmpty()
                                && expressLoadingEntities != null
                                && !expressLoadingEntities.isEmpty()) {
                            for (UnloadScanTable expressLoadingEntity : expressLoadingEntities) {
                                //设置强扫标志，用于颜色标识
                                billDto.setRemark(expressLoadingEntity.getRemark());
                                int weRes = billDto.getWeight().compareTo(BigDecimal.ZERO);
                                if (weRes <= 0) {
                                    billDto.setWeight(expressLoadingEntity.getWeight());
                                }
                                if (expressLoadingEntity.getChargedWeight() != null) {
                                    billDto.setChargedWeight(new BigDecimal(expressLoadingEntity.getChargedWeight()));
                                }
                                //遍历下载的每个子单数据 ，查看是否已扫描
                                for (QueryLoadDetailChildBillcode item : billDto.getChildList()) {
                                    if (item.getChildWaybillNo().equals(expressLoadingEntity.getChildWaybillNo())) {
                                        item.setFlag(1);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                spiltList(unloadDataEntityList);
                //对刷新的列表重新进行排序
                sortList(unloadDataEntityList);
                //识别大票货
                identifyBigTicket();

                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                dismissPgDlg();
                if (isFirstTime) {
                    isFirstTime = false;
                    if (!isScan) {
                        deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
                        if (deptType != 5 && deptType != 6) {
                            //网点卸车倒计时时间，总计费总量 * 4分钟/1000kg = 卸车总时长
                            mUnloadTime = ((int) (chargedWeight * 4) / 1000);
                            //计算倒计时秒数,取余数
                            mUnloadSeconds = (int) ((((chargedWeight * 4) % 1000) / 1000) * 60);
                        } else {
                            //分拨卸车倒计时时间 ，总计费重量 * 1分钟/100KG=卸车总时长
                            mUnloadTime = (int) (chargedWeight / 100);
                            //计算倒计时秒数，取余数
                            mUnloadSeconds = (int) (((chargedWeight % 100) / 100) * 60);
                        }
                        if (chargedWeight <= 3000) {
                            //计费重量小等于3吨，则从30分钟开始倒计时
                            mUnloadTime = 30;
                            mUnloadSeconds = 0;
                            tvUnloadTime.setTextColor(getResources().getColor(R.color.red));
                        }
                        tvUnloadTime.setText(mUnloadTime + ":" + (mUnloadSeconds < 10 ? "0" + mUnloadSeconds : mUnloadSeconds));
                    }
                }
                //开启扫描
                setScannerEnabled(true);
                SoundVibratorManager.playSound(1);
                //根据复选框类型显示运单列表
                showInfosByCheckBox();

                if (isSubmit) {
                    //先刷新数据后，再提交任务
                    submitUnloadTask();
                }
            }

            @Override
            public void onError(Throwable throwable) {
                dismissPgDlg();
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Intent intent = new Intent(UnloadScanActivity.this, UnloadCompareActivity.class);
                Bundle bundle = new Bundle();
                // 打包运单号跳转到对比界面，查看扫描信息
                mQueryLoadDetailBillcode = QueryLoadDetailBillcode.parse(unloadDataEntityList.get(position));
                bundle.putInt("operTypeCode", operTypeCode);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                String waybill = unloadDataEntityList.get(position).getWaybillNo();
                Intent intent = new Intent(UnloadScanActivity.this, DetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("waybill", waybill);
                bundle.putInt("operTypeCode", operTypeCode);
                intent.putExtras(bundle);
                startActivity(intent);
                return true;
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        Intent intent;
        Bundle bundle;
        switch (v.getId()) {
            case R.id.btn_modifyLoadUnloadPeople:
                if (mPalletBindList != null && !mPalletBindList.isEmpty()) {
                    MyDialog.showAlertDialog(UnloadScanActivity.this, "提示", "无法修改装卸人，托盘内有未提交完成的数据！", "确定");
                    return;
                }
                intent = new Intent(this, LoadUnloadGroupActivity.class);
                bundle = new Bundle();
                bundle.putString("carNo", carNo);
                bundle.putString("task", task);
                bundle.putString("deptCode", deptCode);
                bundle.putSerializable("currentDeptCodes", (Serializable) mCurrentDeptCodes);
                bundle.putBoolean("palletBindCheck", cbPalletBind.isChecked());
                //扫描类型：扫描类型：1-装车扫描，2=卸车扫描 ,3-离线装车，4-离线卸车,5-移库装车，6-移库卸车,7-单独移库卸车，
                // 8-分拨自提,9-跨越点货,10-融合装车,11-融合卸车
                bundle.putInt("scanType", Common.SCAN_TYPE_MERGE_UNLOAD);
                //装车类型：1-装车，2-卸车
                bundle.putInt("loadType", 2);
                bundle.putSerializable("carPlaneTasks", (Serializable) mPlanTaskList);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.unload_scan_back:
                if (mPalletBindList != null && !mPalletBindList.isEmpty()) {
                    MyDialog.showAlertDialog(UnloadScanActivity.this, "提示", "无法暂存/返回，托盘内有未提交完成的数据！", "确定");
                    return;
                }
                activityBack();
                break;
            case R.id.unload_refresh:
                loadData(false);
                break;
            case R.id.unload_upload:
                //先刷新数据后，再提交卸车任务
                loadData(true);
                break;
            case R.id.unload_btn_add:
                intent = new Intent(UnloadScanActivity.this, AddBillcodeActivity.class);
                bundle = new Bundle();
                bundle.putInt("operTypeCode", operTypeCode);
                intent.putExtras(bundle);
                startActivityForResult(intent, 0);
                break;
            case R.id.btn_palletBind:
                //托盘绑定
                if (stowageNoMap == null) {
                    showToast("stowageNoMap为空");
                    return;
                }
                if (mPalletBindList == null) {
                    showToast("mPalletBindList为空");
                    return;
                }
                intent = new Intent(UnloadScanActivity.this, PalletBindActivity.class);
                intent.putExtra("palletBindList", (Serializable) mPalletBindList);
                intent.putExtra("task", task);
                startActivityForResult(intent, 0);
                break;
            case R.id.iv_down_layout:
                if (cbChaoChangJian.isChecked() && llFunctionBtn.getVisibility() == View.GONE) {
                    //超长件
                    HiddenAnimUtils.newInstance(this, rgChaoChangJian, null, 30).open();
                } else {
                    HiddenAnimUtils.newInstance(this, rgChaoChangJian, null, 30).close();
                }
                HiddenAnimUtils.newInstance(this, llFunctionBtn, ivDownLayout, 50).toggle();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (mPalletBindList != null && !mPalletBindList.isEmpty()) {
                MyDialog.showAlertDialog(UnloadScanActivity.this, "提示", "无法暂存/返回，托盘内有未提交完成的数据！", "确定");
            } else {
                activityBack();
            }
        }
        return false;
    }

    private void activityBack() {
        String carNo = "";
        List<String> stowageNos = new ArrayList<>();
        CreateStowagesEvent event = new CreateStowagesEvent();
        for (CarPlanTaskEntity planTask : mPlanTaskList) {
            carNo = planTask.getVehNo();
            if (planTask.getLoadTasks() != null) {
                for (LoadBillTaskEntity loadTask : planTask.getLoadTasks()) {
                    stowageNos.add(loadTask.getStowageNo());
                    event.setNextDeptCode(loadTask.getSrcDeptCode());
                    event.setNextDeptCodeName(loadTask.getSrcDeptName());
                }
            }
        }
        event.setCarNo(carNo);
        event.setStowageNos(stowageNos);
        event.setFromActivity(2);

        EventBus.getDefault().post(event);
        finish();
    }

    /**
     * 提交卸车任务
     */
    private void submitUnloadTask() {
        if (unloadDataEntityList == null || unloadDataEntityList.isEmpty()) {
            showToast(getString(R.string.tmp_no_data));
            return;
        }
        //查询是否有扫描的单号
        if (!isLoadScan2(unloadDataEntityList)) {
            showToast(getString(R.string.no_scan_num));
            return;
        }
        //托盘list中有数据不可提交
        if (mPalletBindList != null && !mPalletBindList.isEmpty()) {
            MyDialog.showAlertDialog(UnloadScanActivity.this, "提示", "无法卸车提交，托盘内有未提交完成的数据！", "确定");
            SoundVibratorManager.playSound(2);
            return;
        }

        String msg = "提交后不能再操作,是否提交?";
        for (QueryUnLoadDetailBillcode item : unloadDataEntityList) {
            if (item.getType() == 0 || item.getType() == 1) {
                //标记为红色或者白色为未扫完
                msg = "当前有漏扫的运单，是否强制提交？";
                break;
            }
        }

        MyDialog dialog = new MyDialog(this);
        dialog.setIcon(R.drawable.alert);
        dialog.setMessage(msg);
        dialog.setPositiveClickListener("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //查询是否有扫描的单号
                if (!isLoadScan2(unloadDataEntityList)) {
                    showToast(getString(R.string.no_scan_num));
                    return;
                }
                //PDA完成装卸车任务
//                completeTask();
                isClickSubmit = true;
                upload(null);
            }
        });
        dialog.setNegativeClickListener(R.drawable.btn_cancel_selector, "否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 检测配载单是否有扫描的单号
     */
    protected String isLoadScan(List<QueryUnLoadDetailBillcode> list) {
        Map<String, String> scanStowageNos = new HashMap<>();
        for (String stowageNo : stowageNos) {
            Iterator it = list.iterator();
            while (it.hasNext()) {
                QueryUnLoadDetailBillcode billDto = (QueryUnLoadDetailBillcode) it.next();
                if (billDto.getChildList() != null && !billDto.getChildList().isEmpty()) {
                    boolean isBreak = false;
                    for (QueryLoadDetailChildBillcode item : billDto.getChildList()) {
                        if (item.getStowageNo().equals(stowageNo)) {
                            //查询单号是否扫描
                            if (item.getFlag() == 1) {
                                scanStowageNos.put(stowageNo, stowageNo);
                                isBreak = true;
                                break;
                            }
                        }
                    }
                    if (isBreak) {
                        break;
                    }
                }
            }
        }
        List<String> tempStowageNos = new ArrayList<>();
        tempStowageNos.addAll(stowageNos);
        for (Map.Entry<String, String> entry : scanStowageNos.entrySet()) {
            tempStowageNos.remove(entry.getValue());
        }
        StringBuilder noScanStowageNo = new StringBuilder();
        for (String item : tempStowageNos) {
            noScanStowageNo.append(item + ",");
        }
        String noScanStr = "";
        if (!noScanStowageNo.toString().equals("")) {
            noScanStr = noScanStowageNo.substring(0, noScanStowageNo.length() - 1);
        }
        return noScanStr;
    }

    protected boolean isLoadScan2(List<QueryUnLoadDetailBillcode> list) {
        Iterator it = list.iterator();
        while (it.hasNext()) {
            QueryUnLoadDetailBillcode billDto = (QueryUnLoadDetailBillcode) it.next();
            if (billDto.getChildList() != null && !billDto.getChildList().isEmpty()) {
                for (QueryLoadDetailChildBillcode item : billDto.getChildList()) {
                    //查询单号是否扫描
                    if (item.getFlag() == 1) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * PDA完成装卸车任务
     */
    private void completeTask() {
        //检查扫描数据是否都已上传
        final List<UnloadScanTable> list = mUnloadScanTableDao.getUnUpload(task, operTypeCode);
        if (list == null || list.isEmpty()) {
            uploadTask();
            return;
        }
        for (UnloadScanTable item : list) {
            item.setIsUpload(1);
        }
        //实例化上传类
        ScanLoadUploadRequest mScanLoadUploadRequest = new ScanLoadUploadRequest();
        mScanLoadUploadRequest.setRecords(list);
        //关闭扫描
        setScannerEnabled(false);
        showPgDlg("正在提交扫描数据...");

        new NetRequest().setUrl(Constants.UPLOAD_DATA_POST_URL)
                .setRequestObject(mScanLoadUploadRequest)
                .setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(QueryUnloadDetailResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                        SoundVibratorManager.playSound(2);
                        showToast("提交数据失败：" + msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        //更新数据库状态
                        for (UnloadScanTable item : list) {
                            try {
                                mUnloadScanTableDao.update(item);
                            } catch (SQLException e) {
                                LogUtil.e(e.toString());
                            }
                        }
                        //数据上传后提交任务
                        uploadTask();
                    }
                });
    }

    private void uploadTask() {
        final List<UnloadScanTable> errorList = LoadUtil.getErrorList(mPlanTaskList, mUnloadScanTableDao, operTypeCode);

        if (!errorList.isEmpty()) {
            //查询是否有异常的运单给出提示

            String errorWaybill = "";
            for (UnloadScanTable scanTable : errorList) {
                errorWaybill += scanTable.getChildWaybillNo() + "\n";
            }

            MyDialog.showAlertDialog(this, "运单上传失败，是否放弃该条码？\n" + errorWaybill, "是", "否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    try {
                        DbHelper dbHelper = mUnloadScanTableDao.getDbHelper();
                        if (dbHelper != null && dbHelper.isOpen()) {
                            mUnloadScanTableDao.delete(errorList);
                        }
                    } catch (SQLException e) {
                        LogUtil.e(e.toString());
                    }
                    //设置内存中的数据为未扫描
                    for (UnloadScanTable item : errorList) {
                        //遍历服务器返回数据集合
                        for (QueryUnLoadDetailBillcode billDto : unloadDataEntityList) {
                            if (item.getWaybillNo().equals(billDto.getWaybillNo())) {
                                if (billDto.getChildList() != null) {
                                    Iterator<QueryLoadDetailChildBillcode> it = billDto.getChildList().iterator();
                                    while (it.hasNext()) {
                                        QueryLoadDetailChildBillcode child = it.next();
                                        if (child.getChildWaybillNo().equals(item.getChildWaybillNo())) {
                                            child.setFlag(0);
                                            it.remove();
                                        }
                                    }
                                }
                                billDto.setUcScan(false);
                            }
                        }
                    }

                    //清除托盘绑定中的运单
                    if (mPalletBindList != null) {
                        for (UnloadScanTable item : errorList) {
                            for (QueryUnLoadDetailBillcode detail : mPalletBindList) {
                                if (item.getWaybillNo().equals(detail.getWaybillNo())) {
                                    if (detail.getChildList() != null) {
                                        Iterator<QueryLoadDetailChildBillcode> it = detail.getChildList().iterator();
                                        while (it.hasNext()) {
                                            QueryLoadDetailChildBillcode child = it.next();
                                            if (child.getChildWaybillNo().equals(item.getChildWaybillNo())) {
                                                it.remove();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //发送消息给托盘托盘绑定界面，通知刷新列表
                    sendHandlerToPalletBindActivity();

                    //根据复选框类型显示运单列表
                    showInfosByCheckBox();
                    spiltList(unloadDataEntityList);
                    SoundVibratorManager.playSound(1);
                }
            }, null);
            return;
        }


        //关闭扫描
        setScannerEnabled(false);
        showPgDlg("正在提交卸车任务...");

        //扫描数据上传完后  调完成任务
        FinishTaskUploadRequest mFinishTaskUploadRequest = new FinishTaskUploadRequest();
        mFinishTaskUploadRequest.setStowageNos(mUnloadTaskDao.getStowageNo(task));
        mFinishTaskUploadRequest.setOperTypeCode(operTypeCode);
        mFinishTaskUploadRequest.setOperEmpCode(SharedPreferUtil.getInstance().getValue(Common.USER_CODE));
        mFinishTaskUploadRequest.setUcTaskNos(mUcTaskNoVoList);

        new NetRequest().setUrl(Constants.URL_COMMIT_COMPLETE)
                .setMethod(NetRequest.Method.POST_STRING)
                .setRequestObject(mFinishTaskUploadRequest)
                .setResponsClazz(QueryUnloadDetailResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                        SoundVibratorManager.playSound(2);
                        if (msg != null) {
                            showToast(msg);
                        } else {
                            showToast("提交数据失败");
                        }
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        //更新本地暂存装车任务状态为已完成
                        LoadUtil.updateLoadStatus(task);
                        //计算重量
                        getRealWeight();
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                        //跳转界面
                        Intent unloadScanIntent = new Intent(UnloadScanActivity.this, UnloadSuccessActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("task", task);
                        bundle.putDouble("weight", weight);
                        bundle.putDouble("chargedWeight", chargedWeight);
                        unloadScanIntent.putExtras(bundle);
                        startActivity(unloadScanIntent);

                        for (Activity activity : ActivityStack.getInstance().getActivities()) {
                            if (activity instanceof BlockingUnloadTaskActivity) {
                                activity.finish();
                            }
                        }

                        finish();

                        //发送消息给首页处理待办事项数据，将完成的数据清除
                        LoadUtil.sendEventToSouYe(4, null, mPlanTaskList);
                    }
                });
    }

    //卸车实重
    double weight = 0.0;
    //卸车计重
    double chargedWeight = 0.0;

    private void getRealWeight() {
        weight = 0.0;
        chargedWeight = 0.0;

        for (QueryUnLoadDetailBillcode item : unloadDataEntityList) {
            if (item.getScanCount() > 0) {
                if (item.getChildList() != null) {
                    if ((item.getWaybillNo() + "000").equals(item.getChildList().get(0).getChildWaybillNo())) {
                        //大票货
                        weight += BigDecimalUtils.round(item.getWeight().doubleValue(), 4);
                        chargedWeight += BigDecimalUtils.round(item.getChargedWeight().doubleValue(), 4);
                    } else if ("2".equals(item.getWaybillType())) {
                        //整车单
                        weight += BigDecimalUtils.round(item.getWeight().doubleValue(), 4);
                        chargedWeight += BigDecimalUtils.round(item.getChargedWeight().doubleValue(), 4);
                    } else {
                        //正常单
                        weight += BigDecimalUtils.mul(BigDecimalUtils.div(item.getWeight().doubleValue(), item.getSrcPiecesNum(), 4), item.getScanCount());
                        chargedWeight +=
                                BigDecimalUtils.mul(BigDecimalUtils.div(item.getChargedWeight().doubleValue(), item.getSrcPiecesNum(), 4), item.getScanCount());
                    }
                }
            }
        }
        weight = BigDecimalUtils.round(weight, 2);
        chargedWeight = BigDecimalUtils.round(chargedWeight, 2);
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveUnloadCountDown();
        //停止刷新
        if (checkTimeHandler != null) {
            checkTimeHandler.removeCallbacks(runnable);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (stowageNoMap != null) {
            //清空静态数据，释放内存
            stowageNoMap.clear();
            stowageNoMap = null;
        }
        //停止刷新
        if (checkTimeHandler != null) {
            checkTimeHandler.removeCallbacks(runnable);
        }
        if (unloadDataEntityList != null) {
            unloadDataEntityList.clear();
        }
        chaoChangJian = null;
        //退出上传
        isExit = true;
        //保存卸车倒计时
        saveUnloadCountDown();

        //取消注册事件
        EventBus.getDefault().unregister(this);

        BlueToothUtil.INSTANCE.setListener(null);
        BlueToothUtil.INSTANCE.disConnect();
    }

    @Override
    public void finish() {
        super.finish();
        //退出上传
        isExit = true;
    }

    /**
     * 快递称重获取重量
     *
     * @param string 重量值
     */
    @Override
    public void getValue(@NotNull final String string) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    double textValue = Double.parseDouble(string.trim());
                    mUcWeight = new BigDecimal(textValue + "");
                    if (textValue > 300) {
                        if (!WarnFragment.INSTANCE.isShowing()) {
                            WarnFragment.INSTANCE.show();
                        }
                    } else {
                        if (WarnFragment.INSTANCE.isShowing()) {
                            WarnFragment.INSTANCE.dismiss();
                        }
                    }
                    WeightErrorPresenter.getInstance().dissMissDialog();
                } catch (Exception e) {
                    e.printStackTrace();
                    mUcWeight = new BigDecimal(0);
                    WeightErrorPresenter.getInstance().showWeightError(UnloadScanActivity.this);
                }
            }
        });
    }

    @Override
    public void successConnect() {
        ToastUtil.showToast("电子秤已连接");
        isBlueConnected = true;
    }

    @Override
    public void successDis() {
        ToastUtil.showToast("电子秤断开");
        isBlueConnected = false;
    }

    /**
     * 保存卸车倒计时
     */
    private void saveUnloadCountDown() {
        try {
            LoadUnloadTimeTable timeTable =
                    loadUnloadTimeTableDao.getData(sharedPreferUtil.getValue(Common.USER_CODE), sharedPreferUtil.getCompanyCode(), task);
            if (timeTable != null) {
                if (timeTable.getIsScan() == 1 || isScan) {
                    timeTable.setScanRemainTime(tvUnloadTime.getText().toString());
                    timeTable.setIsScan(1);
                    loadUnloadTimeTableDao.update(timeTable);
                }
            } else {
                LoadUnloadTimeTable loadUnloadTimeTable = new LoadUnloadTimeTable();
                //装车类型：2-卸车
                loadUnloadTimeTable.setLoadType(2);
                //1-已扫描
                if (isScan) {
                    loadUnloadTimeTable.setIsScan(1);
                }
                String unloadTime = tvUnloadTime.getText().toString();
                String[] unloadTimeSplit = unloadTime.split(":");
                long minutes = Long.parseLong(unloadTimeSplit[0]);
                long seconds = Long.parseLong(unloadTimeSplit[1]);
                Date currentDate = new Date();
                //计算卸车完成的时间点
                Date unloadFinishTime = new Date(currentDate.getTime() + minutes * 60 * 1000 + seconds * 1000);
                loadUnloadTimeTable.setUnloadFinishTimePoint(DateHelper.getDateTimeFormate(unloadFinishTime));
                loadUnloadTimeTable.setScanRemainTime(tvUnloadTime.getText().toString());
                loadUnloadTimeTable.setUserCode(sharedPreferUtil.getValue(Common.USER_CODE));
                loadUnloadTimeTable.setCompCode(sharedPreferUtil.getCompanyCode());
                loadUnloadTimeTable.setUnloadTaskNo(task);
                loadUnloadTimeTableDao.insert(loadUnloadTimeTable);
            }
        } catch (Exception e) {
            LogUtil.e(e.toString());
        }
        //关闭卸车倒计时
        if (mTimer != null) {
            mTimer.cancel();
        }
        isScan = false;
    }

    /**
     * 处理服务器数据，配载单数据修改为Map<配载单号，运单明细/包 集合>
     */
    private void spiltList(List<QueryUnLoadDetailBillcode> list) {
        if (stowageNoMap != null) {
            stowageNoMap.clear();
        } else {
            stowageNoMap = new HashMap<>();
        }
        for (QueryUnLoadDetailBillcode unLoadDetailBillcode : list) {
            try {
                if (!stowageNoMap.containsKey(unLoadDetailBillcode.getStowageNo())) {
                    stowageNoMap.put(unLoadDetailBillcode.getStowageNo(), new ArrayList<QueryUnLoadDetailBillcode>());
                }
                if (stowageNoMap.get(unLoadDetailBillcode.getStowageNo()) != null) {
                    stowageNoMap.get(unLoadDetailBillcode.getStowageNo()).add(unLoadDetailBillcode);
                }
            } catch (Exception e) {

            }
        }
    }

    /**
     * 识别大票货
     */
    private void identifyBigTicket() {
        if (stowageNoMap != null) {
            for (Map.Entry<String, List<QueryUnLoadDetailBillcode>> entry : stowageNoMap.entrySet()) {
                if (entry.getValue() != null && !entry.getValue().isEmpty()) {
                    for (QueryUnLoadDetailBillcode detailBillcode : entry.getValue()) {
                        if (detailBillcode.getChildList() != null && !detailBillcode.getChildList().isEmpty()) {
                            String childWaybillNo = detailBillcode.getChildList().get(0).getChildWaybillNo();
                            if ("000".equals(childWaybillNo.replace(detailBillcode.getWaybillNo(), ""))) {
                                detailBillcode.setBigTicket(true);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 添加托盘绑定数据
     *
     * @param result               子单号
     * @param unLoadDetailBillcode 运单实体
     * @param cancleStatu          绑定标识 1-第一次绑定 ,2-第二次绑定
     */
    private void addPalletBindData(String result, QueryUnLoadDetailBillcode unLoadDetailBillcode, int cancleStatu) {
        if (cbPalletBind.isChecked()) {
            //非强扫状态绑定数据
            if (mPalletBindList == null) {
                mPalletBindList = new ArrayList<>();
            }
            //判断是否超过五个不同库区的运单，超过则中断提示
            Map<String, String> map = new HashMap<>();
            for (QueryUnLoadDetailBillcode entity : mPalletBindList) {
                if (map.get(unLoadDetailBillcode.getAreaCode()) == null) {
                    map.put(entity.getAreaCode(), entity.getAreaCode());
                    if (map.size() >= 5) {
                        if (PalletBindActivity.mHandler != null) {
                            PalletBindActivity.mHandler.sendEmptyMessage(PalletBindActivity.HANDLER_101);
                        } else {
                            MyDialog.showAlertDialog(this, "提示", "已超过一个托盘额定绑定票数，请使用托盘绑定！", "确定");
                        }
                        return;
                    }
                }
            }

            //查询托盘list中的运单
            boolean hasWayBillNo = false;
            QueryUnLoadDetailBillcode queryUnLoadDetailBillcode = null;
            for (QueryUnLoadDetailBillcode entity : mPalletBindList) {
                if (result.startsWith(entity.getWaybillNo())) {
                    queryUnLoadDetailBillcode = entity;
                    hasWayBillNo = true;
                    break;
                }
            }
            unLoadDetailBillcode.setForliftNo(mPalletTaskNo);
            //绑定标识 1-第一次绑定 ,2-第二次绑定
            unLoadDetailBillcode.setCancleStatu(cancleStatu);
            unLoadDetailBillcode.setInputType(inputType);
            unLoadDetailBillcode.setOperTime(Constants.GetScanTime());
            if (!hasWayBillNo) {
                //添加不存在的运单至托盘中
                if (unLoadDetailBillcode.getChildList() != null) {
                    for (QueryLoadDetailChildBillcode childEntity : unLoadDetailBillcode.getChildList()) {
                        if (result.equals(childEntity.getChildWaybillNo())) {
                            childEntity.setPalletBindFlag(1);
                            break;
                        }
                    }
                }
                mPalletBindList.add(unLoadDetailBillcode);
            } else {
                //修改已存在托盘中的运单的绑定状态为已扫描状态
                if (queryUnLoadDetailBillcode.getChildList() != null) {
                    for (QueryLoadDetailChildBillcode childEntity : queryUnLoadDetailBillcode.getChildList()) {
                        if (result.equals(childEntity.getChildWaybillNo())) {
                            if (childEntity.getPalletBindFlag() == 1) {
                                return;
                            }
                            childEntity.setPalletBindFlag(1);
                            break;
                        }
                    }
                }
            }
            //发送消息给托盘绑定界面，通知刷新列表
            sendHandlerToPalletBindActivity();
        }
    }

    /**
     * 发送消息给托盘托盘绑定界面，通知刷新列表
     */
    private void sendHandlerToPalletBindActivity() {
        Bundle bundle = new Bundle();
        bundle.putSerializable("palletBindList", (Serializable) mPalletBindList);
        Message msg = new Message();
        msg.what = PalletBindActivity.HANDLER_100;
        msg.setData(bundle);
        if (PalletBindActivity.mHandler != null) {
            //在托盘绑定界面扫描时，发送消息，更新托盘绑定界面数据
            PalletBindActivity.mHandler.sendMessage(msg);
        }
    }

    class ListViewAndHeadViewTouchLinstener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            //当在列头 和 listView控件上touch时，将这个touch的事件分发给 ScrollView
            HorizontalScrollView headSrcrollView = (HorizontalScrollView) listHead.findViewById(R.id.horizontalScrollView1);
            headSrcrollView.onTouchEvent(arg1);
            return false;
        }
    }

    /**
     * 数据排序
     * 一级排序 红>白>黄>绿,getType
     * 二级排序 必-时-跨-串-快递-空
     */
    private List<QueryUnLoadDetailBillcode> sortList(List<QueryUnLoadDetailBillcode> list) {
        for (QueryUnLoadDetailBillcode item : list) {
            //设置一级排序
            item.setFirstSort(item.getType());
            //设置二级排序
            item.setSecondSort(Common.setSecondType(item.getProductType(), item.getGoodsPriority(), item.getWaybillNo()));
        }
        String[] sortNameArr = {"firstSort", "secondSort"};
        // true升序,false降序
        boolean[] isAscArr = {true, true};
        ListUtils.sort(list, sortNameArr, isAscArr);
        return list;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public synchronized void onMoonEvent(CountEvent countEvent) {
        num.setText(countEvent.getCount() + "");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(ScanResult scanResult) {
        if (scanResult.getOperSource() == 7 && scanResult.getOperType() == 7) {
            if (UcWaybillValidate.validate(scanResult.getResult())) {
                handleScanResult(scanResult.getResult());
            } else {
                showToast("非快递运单不支持手动添加");
                SoundVibratorManager.playSound(2);
            }
        }
    }
}
